ASP.NET MVC > Passing data

Access data from querystring to action method in ASP.NET MVC

How to access data from querystring to the controller action method?


There are at least two ways to retrieve querystring data into the Controller action method.

  • Using parameter of the action method
  • Using Request.QueryString

BROWSER ADDRESS BAR URL

http://localhost:63087/SessionStateManagement/Details?id=50&name=itfunda
Notice that we are passing id as querystring and its value is 50 and another querystring is name and it's value is "itfunda".

ACTION METHOD CODE

public ActionResult Details(int id)
     {
         ViewBag.Id = id;
         ViewBag.Name = Request.QueryString["name"];
         return View();
     }

In the above code, we are accessing the “id” querystring by the action method parameter and “name” querystring by using Request.QueryString object.

VIEW CODE

<h2>Details</h2>
The querystring value is <strong>@ViewBag.Id</strong>
<p>
       @Request.QueryString["id"]
</p>
<p>@ViewBag.Name</p>

@Request.QueryString["name"]

In the View, querystring can be accessed directly using @Request.QueryString also.

 Views: 55865 | Post Order: 60



Write for us






Hosting Recommendations