Monday, May 12, 2014

Passing QueryString Parameters to an ASP.NET MVC Controller


If you have to pass QueryString parameters to an ASP.NET MVC Controller, you need to use RouteValues.
RouteValues is the method of passing values to a controller.  In order to construct a Url with RouteValues to include in a QueryString, you can write something like the following:
 @Html.ActionLink("Shopping Cart", "ShoppingCart", "Registration", new {@eventId=241, @task="register"}, null)  

The above code passes the eventId and task values as QueryString parameters.

Your resulted constructed Url will look like the following:

http://localhost/Registration/ShoppingCart?eventId=241&task=register

Now, to handle the code in the Controller, you can write something like the following:


[HttpGet]

        public ActionResult ShoppingCart(string eventId, string task)

        {

 

            ViewBag.EventID = eventId;

            ViewBag.Task = task;

 

            return View();

        }


This will allow you to accept both parameters passed in the QueryString and then attach them to the ViewBag (or a model) for using in your View.

The code above will also work just fine if NO QueryString parameters are available.

Of course, if you want to dynamically handle QueryStrings because the number of values may differ, it may be easier to simply have a Controller method such as the following:


[HttpGet]

       public ActionResult ShoppingCart()

       {

 

           if (Request.QueryString.Count > 0)

           {

               string eventId = Request.QueryString["eventId"];

               string task = Request.QueryString["task"];

 

               ViewBag.EventID = eventId;

               ViewBag.Task = task;

           }

 

 

           return View();

       }


The above code simply pulls the QueryString values out of the Request object (similar to how this was done in ASP.NET Web Forms).

Once again you can process these values by attaching them to the ViewBag or to a model based on your needs.

That is all there is to it!

No comments:

Post a Comment