如何在MVC4中更改控制器中的参数名称?

时间:2013-12-31 05:59:21

标签: c# asp.net asp.net-mvc-4

我有一个如下控制器:

public class PostsController : Controller
{
    public ActionResult Index(int CategoryID)
    {
        return Content(CategoryID.ToString());
    }
}

我的路由器是:

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 }
    );
 }

我想将MapRoute添加到RegisterRoutes中,如下所示:

routes.MapRoute(
    name: "Posts",
    url: "Posts/{action}/{CategoryID}",
    defaults: new { controller = "Posts", action = "Index", CategoryID = UrlParameter.Optional }
);

我转到 /帖子/索引/ 1 网址,但我发出以下错误:

参数字典包含非可空类型'System.Int32'参数'CategoryID'的空条目

注意:在控制器中如果我将 CategoryID 更改为 id 问题已解决,那就有效了!

1 个答案:

答案 0 :(得分:2)

正如@Davide Icardi所说,您需要将新路线置于默认路线之上。

从头到尾评估路线;将使用匹配的第一个。将特定于帖子控制器的路由放置在列表顶部将保证它在默认路由之前匹配。