C# 参数字典包含不可为空类型的参数“id”的空条目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11686528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:49:40  来源:igfitidea点击:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type

c#asp.net-mvcroutesactionresult

提问by dtsg

I'm trying to retrieve data from my db via the idparameter in my default route:

我正在尝试通过id默认路由中的参数从我的数据库中检索数据:

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

In this ActionResult I'm trying to render a custom user control, based on the route id parameter so that I retrieve the relevant data for the page that's requested

在此 ActionResult 中,我尝试根据路由 id 参数呈现自定义用户控件,以便检索所请求页面的相关数据

public ActionResult InitPageNav(int id)
{
      PageModel page = PageNavHelper.GetPageByID(id);
      return PartialView("UserControls/_PageNavPartial", page);
}

Edit*

编辑*

public static MvcHtmlString CreateMenuItems(this HtmlHelper helper, string action, string text)
{
     var menuItem = new TagBuilder("li");
     var link = new TagBuilder("a");

     //Get current action from route data
     var currentAction = (string)helper.ViewContext.RouteData.Values["action"];
     link.Attributes.Add("href", string.Format("/Home/{0}", action));

     if (currentAction == action)
     {
         menuItem.AddCssClass("selected");
         link.Attributes.Remove("href");
         link.Attributes.Add("href", string.Format("/Home/{0}", currentAction.ToString()));
     }

     link.SetInnerText(text);
     menuItem.InnerHtml = link.ToString();

     return MvcHtmlString.Create(menuItem.ToString());
 }

But I keep getting the error:

但我不断收到错误消息:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type

Can anyone spot where I'm going wrong?

谁能发现我哪里出错了?

采纳答案by Steen T?ttrup

To call the action, an integer is needed in the URL, like so: /Home/InitPageNav/1

要调用该操作,URL 中需要一个整数,如下所示:/Home/InitPageNav/1

Either that or you change the action method to allow for a nullable integer (but that doesn't make sense, unless you have a default page you can retrieve if no id was given?).

或者您更改操作方法以允许可以为空的整数(但这没有意义,除非您有一个默认页面,如果没有给出 id 就可以检索?)。

If you don't want a page id in the url, you need something else to identify the page, like the title??

如果您不想在 url 中包含页面 ID,则需要其他内容来标识页面,例如标题?

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{title}", // URL with parameters
            new { controller = "Home", action = "Index", title = UrlParameter.Optional } // Parameter defaults
        );

and the action:

和行动:

public ActionResult InitPageNav(String title)
{
      PageModel page = PageNavHelper.GetPageByTitle(title);
      return PartialView("UserControls/_PageNavPartial", page);
}

Just make sure to handle the case where the title parameter is empty/null. And generally you should use the helpers/extensions already present in the Mvc framework for building your urls.

只要确保处理 title 参数为空/空的情况。通常你应该使用 Mvc 框架中已经存在的帮助器/扩展来构建你的 url。

@Html.ActionLink("Link text", "action", "controller", new { title = "whatever" }, null)

or in your more advanced helper,

或者在你更高级的助手中,

public static MvcHtmlString CreateMenuItems(this UrlHelper url, string action, string text)
{
     var menuItem = new TagBuilder("li");
     var link = new TagBuilder("a");

     //Get current action from route data
     var currentAction = (string)helper.RequestContext.RouteData.Values["action"];
     link.Attributes.Add("href", url.Action(action, "home", new { title = "whatever" }));

     if (currentAction == action)
     {
         menuItem.AddCssClass("selected");
     }

     link.SetInnerText(text);
     menuItem.InnerHtml = link.ToString();

     return MvcHtmlString.Create(menuItem.ToString());
 }

回答by hiddenbyte

If the exception/error is thrown by the ASP .NET MVC Framework, then the reason of this exception is that 'id' parameter is not being passed on the HTTP request.

如果异常/错误是由 ASP .NET MVC 框架引发的,则此异常的原因是HTTP 请求中未传递 'id' 参数

Try to redefine the action method signature to the following:

尝试将操作方法​​签名重新定义为以下内容:

    public ActionResult InitPageNav(int? id) //id is now a nullable int type
    {
          if(!id.HasValue) //id parameter is set ?
          {
                //return some default partial view or something 
          }

          PageModel page = PageNavHelper.GetPageByID(id);
          return PartialView("UserControls/_PageNavPartial", page);
    }

EDIT: If you think that is more useful to change the id parameter type to 'string', then you just have to change the action method signature.

编辑:如果您认为将 id 参数类型更改为“字符串”更有用,那么您只需更改操作方法签名。