Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4: Multiple Controller action parameters

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?

like image 622
Alex Guerin Avatar asked Feb 21 '23 20:02

Alex Guerin


2 Answers

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)
{
    // ...
}
like image 120
McGarnagle Avatar answered Feb 23 '23 09:02

McGarnagle


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

like image 25
Joe Alfano Avatar answered Feb 23 '23 09:02

Joe Alfano