Instead of just {controller}/{action}/{id}
is it possible to have mulitple parameters like
{controller}/{action}/{id}/{another id}
?
I'm new to MVC (coming from just plain Web Pages). If not possible, does MVC provide a helper method like the UrlData
availble in Web Pages?
You will just need to map the new route in your global.asax, like this:
routes.MapRoute(
"NewRoute", // Route name
"{controller}/{action}/{id}/{another_id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional, another_id = UrlParameter.Optional } // Parameter defaults
);
Then in your controller's action you can pick up the parameter like this:
public ActionResult MyAction(string id, string another_id)
{
// ...
}
Yes, you can define multiple parameters in a route. You will need to first define your route in your Global.asax file. You can define parameters in URL segments, or in portions of URL segments. To use your example, you can define a route as
{controller}/{action}/{id1}/{id2}
the MVC infrastructure will then parse matching routes to extract the id1 and id2 segments and assign them to the corresponding variables in your action method:
public class MyController : Controller
{
public ActionResult Index(string id1, string id2)
{
//..
}
}
Alternatively, you could also accept input parameters from query string or form variables. For example:
MyController/Index/5?id2=10
Routing is discussed in more detail here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With