Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending multiple parameters to Actions in ASP.NET MVC

Tags:

I'd like to send multiple parameters to an action in ASP.NET MVC. I'd also like the URL to look like this:

http://example.com/products/item/2 

instead of:

http://example.com/products/item.aspx?id=2 

I'd like to do the same for sender as well, here's the current URL:

http://example.com/products/item.aspx?id=2&sender=1 

How do I accomplish both with C# in ASP.NET MVC?

like image 926
Reza Avatar asked Jan 03 '11 16:01

Reza


People also ask

How do I pass more than one parameter in a URL?

URL parameters are made of a key and a value, separated by an equal sign (=). Multiple parameters are each then separated by an ampersand (&).

How do I pass multiple parameters to Web API controller methods?

You can pass parameters to Web API controller methods using either the [FromBody] or the [FromUri] attributes. Note that the [FromBody] attribute can be used only once in the parameter list of a method.


1 Answers

If you're ok with passing things in the query string, it's quite easy. Simply change the Action method to take an additional parameter with a matching name:

// Products/Item.aspx?id=2 or Products/Item/2 public ActionResult Item(int id) { } 

Would become:

// Products/Item.aspx?id=2&sender=1 or Products/Item/2?sender=1 public ActionResult Item(int id, int sender) { } 

ASP.NET MVC will do the work of wiring everything up for you.

If you want a clean looking URL, you simply need to add the new route to Global.asax.cs:

// will allow for Products/Item/2/1 routes.MapRoute(         "ItemDetailsWithSender",         "Products/Item/{id}/{sender}",         new { controller = "Products", action = "Item" } ); 
like image 107
Justin Niessner Avatar answered Oct 20 '22 23:10

Justin Niessner