【问题标题】:The parameters dictionary contains a null entry for parameter 'id' when change in Routing当路由更改时,参数字典包含参数“id”的空条目
【发布时间】:2015-06-21 17:47:54
【问题描述】:

我已经在我的 routeConfig 文件中完成了路由,如下所示。

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Search",
                url: "{controller}/{action}/{department}/{name}",
                defaults: new { controller = "Search", action = "Result",name =UrlParameter.Optional}
                );

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

我只希望 name 参数应该是可选的,所以写这个

name =UrlParameter.Optional

但是现在当我点击这个链接时

@Html.ActionLink("Edit", "EditEmployee", new { id = item.Id })

它给了我例外“The parameters dictionary contains a null entry for parameter 'id'

案例 1: 但是当我这样做时,

defaults: new { controller = "Search", action = "Result"}

删除名称可选,它工作正常。

案例 2: 当我这样做时

defaults: new { controller = "Search", action = "Result", department =UrlParameter.Optional, name=UrlParameter.Optional}

使这两个参数都是可选的,也可以正常工作,但是现在为Edit生成的Url如下

http://localhost:12190/Home/EditEmployee?id=1

但我想要这样干净的 URL http://localhost:12190/Home/EditEmployee/1.

那么如何才能获得两者,只有名称参数可选,还有一个干净的 URL。

【问题讨论】:

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


    【解决方案1】:

    您有两条路线,似乎您在脑海中混合了它们。您提供的路径 (http://localhost:12190/Home/EditEmployee?id=1) 指的是第二条路线,而 departmentname 参数 - 指的是第一条路线。

    也许您需要注释第一条路线并尝试使用您的参数集 - actionid 让一切正常。您也可以尝试使用属性路由来指定控制器和操作的路由

    【讨论】:

      猜你喜欢
      • 2017-05-12
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      相关资源
      最近更新 更多