VSB
VSB

Reputation: 10415

ASP.NET MVC: parameter is not passed during URL routing

I defined the below routes to have friendly urls in my RouteConfig.cs:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
    name: "CreateChildRoute",
    url: "Admin/MaterialPaymentRequestSbuItem/CreateChild/{parentId}",
    defaults: new { controller = "MaterialPaymentRequestSbuItem", action = "CreateChild", parentId = UrlParameter.Optional }
); 
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    namespaces: new[] {"ProjectManager.Controllers"}

);

However when I call: http://localhost:46813/Admin/MaterialPaymentRequestSbuItem/CreateChild/23 A null value is passed to controller:

public ActionResult CreateChild(int? parentId){
  .....
} 

But calling http://localhost:46813/Admin/MaterialPaymentRequestSbuItem/CreateChild?parentId=32 Works with no problem and passes the parameter as it supposed to be.

P.S. Admin is a defined area in my application. Here is output of Route Debugger for http://localhost:46813/Admin/MaterialPaymentRequestSbuItem/CreateChild?parentId=2: enter image description here

Upvotes: 0

Views: 1043

Answers (1)

Mo09890
Mo09890

Reputation: 174

From what I can see your route table looks to be correct, there's a typo in there but it seems to be pretty consistent throughout so I'm guessing that's not a problem.

Contrary to what teo van kot says you always want to start with the most specific routes first and have the more general ones come last as only the first route to match will be used.

A useful tool I've used to debug my routes is the Route Debugger from Phil Haak. It lets you see what route was chosen and, more usefully which parameters were mapped, and can be installed via NuGet

Upvotes: 4

Related Questions