Home > DeveloperSection > Forums > Redirecting when the querystring is empty
Chris S
Chris S

Total Post:48

Points:336
Posted on    June-01-2015 12:46 AM

 .NET C#  ASP.Net 
Ratings:


 1 Reply(s)
 497  View(s)
Rate this:

In my sample I have two controllers for a bus service the bus routes and bus route stops. if a route hasn't been selected I need to redirect back to the bus route index. I

When I go directly to the bus route stop controller it should throw me back to the bus route list but it doesn't.

 

public ActionResult Index()

        {

            string busRouteCode = "";

            //checks query string to see if empty

            if (Request.QueryString == null)

            {

                //checks the cookies to see if empty

                if (Request.Cookies["busRouteCode"] == null)

                    {

                    //if empty returns to bus route controller.

                     return View("index", "snBusRoutes");

                    }

                else

                    {

                        busRouteCode = Response.Cookies["busRouteCode"].Value;   

                    }                            

            }

            else

            {

              busRouteCode = Request.QueryString["busRouteCode"]; 

            }

            var routeStops = db.routeStops.Include(r => r.busRoute).Include(r => r.busStop);

            return View(routeStops.ToList());

        }



Monaj Singh
Monaj Singh

Total Post:41

Points:287
Posted on    June-01-2015 1:10 AM

I don't think Request.QueryString in its entirety is ever going to be null. Though a specific value may be null or empty. Something like this:

 

if (string.IsNullOrWhiteSpace(Request.QueryString["busRouteCode"]))

    if (string.IsNullOrWhiteSpace(Request.Cookies["busRouteCode"]))

        return View("index", "snBusRoutes");

Update: Semantically it's probably better to perform a redirect than to return the view in this case. The user is making a specific request, but that request directs them somewhere else. They should know they're going somewhere else. Something like this:

 

if (string.IsNullOrWhiteSpace(Request.QueryString["busRouteCode"]))

    if (string.IsNullOrWhiteSpace(Request.Cookies["busRouteCode"]))

        return RedirectToAction("index", "controllerName");


Modified On Apr-04-2016 07:49:10 AM

Don't want to miss updates? Please click the below button!

Follow MindStick