Alex Guerin
Alex Guerin

Reputation: 2386

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?

Upvotes: 4

Views: 14831

Answers (2)

McGarnagle
McGarnagle

Reputation: 102793

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)
{
    // ...
}

Upvotes: 4

Joe Alfano
Joe Alfano

Reputation: 10299

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

Upvotes: 4

Related Questions