Pass Parameter Or Query String In Action Method In ASP.NET MVC

Before proceeding, I recommend you to read the previous article of this series i.e. Create First Application in ASP.NET MVC 4.0. In this article, we will learn how to pass parameter or Query String in an Action Method in ASP.NET MVC.
 
Let's Begin:
  1. Create a new ASP.NET MVC 4 Empty Project.

  2. Add a controller and name it HomeController, then Add Index Action Method to it. If you don't know how to create or how to add controller read it here.

  3. Pass parameter in Index Action Method.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace PassParameter.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         //  
  12.         // GET: /Home/  
  13.   
  14.         public string Index(string id)  
  15.         {  
  16.             return "ID =" + id;  
  17.         }  
  18.   
  19.     }  
  20. }  
In the above code, we have passed a parameter named as the id of string data type. Now Build & Run the application and open http://localhost:13923/Home/Index/10 link in the URL by passing the parameter to Index Action Method of Home Controller.
 
Preview:

 

Passing Multiple Parameter in Index Action Method:

In the above example, we saw how to pass single parameter in Action Method, but there are many situations when we have to pass more than one parameter. Let's see how to do this in ASP.NET MVC.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace PassParameter.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.   
  12.         public string Index(string id, string name)  
  13.         {  
  14.             return "ID =" + id+"<br /> Name="+name;  
  15.         }  
  16.   
  17.     }  
  18. }  
In the above code, we have added/passed multiple parameters (two) in Index Action method. Name of the parameter in the URL must match with the name of the parameter in the Action Method.

Preview:

 

We can also get the QueryString values using Request.QueryString Collection.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace PassParameter.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.   
  12.         public string Index(string id)  
  13.         {  
  14.             return "ID =" + id+"<br /> Name="+Request.QueryString["name"].ToString();  
  15.         }  
  16.   
  17.     }  
  18. }  
Preview: 

 

I hope you enjoyed this post. Thanks!


Similar Articles