[英]How to change parameter name in controller in MVC4?
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: 我想像这样将MapRoute添加到RegisterRoutes中:
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: 我转到/ Posts / Index / 1网址,但出现以下错误:
The parameters dictionary contains a null entry for parameter 'CategoryID' of non-nullable type 'System.Int32' 参数字典包含非空类型“ System.Int32”的参数“ CategoryID”的空条目
Note: in controller if I change CategoryID to id problem solved, and it worked! 注意:在控制器中,如果我将CategoryID更改为id,则问题已解决,并且可以正常工作!
As @Davide Icardi said, you need to place your new route above the default route. 正如@Davide Icardi所说,您需要将新路线放置在默认路线上方。
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.
将特定于Posts控制器的路由放在列表顶部将确保在默认路由之前匹配该路由。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.