Reputation: 9414
I have a Controller like following:
public class PostsController : Controller
{
public ActionResult Index(int CategoryID)
{
return Content(CategoryID.ToString());
}
}
And my router is:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
I wants add a MapRoute into RegisterRoutes like this:
routes.MapRoute(
name: "Posts",
url: "Posts/{action}/{CategoryID}",
defaults: new { controller = "Posts", action = "Index", CategoryID = UrlParameter.Optional }
);
I go to /Posts/Index/1 url but I give following error:
The parameters dictionary contains a null entry for parameter 'CategoryID' of non-nullable type 'System.Int32'
Note: in controller if I change CategoryID to id problem solved, and it worked!
Upvotes: 1
Views: 309
Reputation: 8475
As @Davide Icardi said, you need to place your new route above the default route.
Routes are evaluated from first to last; the first one to match will be used. Placing the route specific to the Posts controller at the top of the list will guarantee that it is matched before the default route.
Upvotes: 2