In this article, we will learn about using query string in ASP.NET MVC with example. Generally, the query string is used to pass data from one page to another page using URL. The data passed using query string are visible in the browser.
In ASP.NET MVC query string is supported by routing which is configured in RouteConfig.cs file as an optional attribute.
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Demo", action = "Index", id = UrlParameter.Optional } ); } }
As we can see that {id} is configured as UrlParameter.Optional which means that the query string is optional to pass.
Example of a Query string
http://localhost:5000/Demo/index?Name=Test&&Age=55
Now let us see this by example.
Now create a new method in controller and add some parameters in it.
[HttpGet] public ActionResult Demo(string Name,string Age) { string result = Name + " " + Age; return Content(result); }
Output:
We can also call the query string method using the @Html.ActionLink()
[HttpGet] public ActionResult DemoActionLink(string name, string age) { return View(); }
Now add the code in DemoActionLink.cshtml
@{ ViewBag.Title = "DemoActionLink"; Layout = null; } @Html.ActionLink("Call Query String","DemoActionLink", new { Name = "Faisal", Age = "18" })
Output: