【问题标题】:"The parameters dictionary contains a null entry..." Error“参数字典包含一个空条目......”错误
【发布时间】:2013-06-06 18:50:16
【问题描述】:

基本上我是一个 Winforms 人。学习 ASP.Net 和 MVC 并陷入一个问题。

我的页面名称为 Calculation。内容如下

<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server">
    <h2>About</h2>
    <p>
        <%: ViewData["Message"] %>
    </p>
</asp:Content>

HomeController.cs

    public ActionResult Calculation(int value)
    {
        ViewData["Message"] = String.Format("{0} when squared produces {1}", value, Models.Mathematics.Square(value));
        return View();
    }

我按下ctrl+5 并进入我的主页。单击计算页面并收到错误

The parameters dictionary contains a null entry for parameter 'value' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Calculation(Int32)' in 'MathSolution.Controllers.HomeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters

我尝试过 http://localhost:3670/Home/Calculation/5 还有 http://localhost:3670/Home/Calculation?value=5。我仍然收到错误。我还尝试将 HttpPost 放在 HomeController.cs 中的 Calculation 方法上。

但是,如果在 HomeContoller.cs 文件计算方法中我为参数设置了一个默认值,那么错误就会消失并且我总是得到默认值。

老实说,我的教程能够使它工作,但我不确定我的解决方案有什么问题。如果您需要更多信息,请告诉我。

【问题讨论】:

  • 我是否必须对我机器上的 IIS 进行任何更改......或者没关系......?
  • 你在使用 MVC 和 WebForms 控件吗?使用 Razor 使用纯 MVC 可能会更好。看起来您的路由可能无法正常工作。检查您的RouteConfig.cs
  • 尝试将参数名称更改为“id”,例如:public ActionResult Calculation(int id)... 或在 global.asax.cs 中添加路由...stackoverflow.com/questions/155864/…
  • 我认为@Mate 有它——MVC 中的默认路由使用“id”作为参数名称。您可以在 Global.asax.cs 文件中看到这一点 - 从那里,您可以根据需要更改它,或添加其他路线,但您最简单的解决方案就是使用“id”。
  • 使用 id 有效。但是当我单击Calculation 页面时为什么会出现错误?我可以在 Global.asax.cs 文件中看到该参数设置为可选。为什么我没有得到我的默认页面?

标签: c# html asp.net asp.net-mvc parameters


【解决方案1】:

最简单的解决方案,不一定是最好的:尝试将参数名称更改为 'id'

public ActionResult Calculation(int id)
        {
            ViewData["Message"] = String.Format("{0} when squared produces {1}", id, Models.Mathematics.Square(id));
            return View();
        }

查看this 以获得更准确的解释

【讨论】:

  • HttpPost 放在计算方法的顶部也解决了默认页面。再次感谢。
【解决方案2】:

你要么需要给你的参数一个默认值:

public ActionResult Calculation(int value = 0)

或者将其设为可空类型:

public ActionResult Calculation(int? value)

因为它是一个整数,所以它不能为空,这就是路由中没有指定值时的样子。

【讨论】:

  • 感谢 Ninlar 的努力。但我认为传递默认值只会有助于避免错误,因为我总是会根据默认值本身获得结果,因为真正的问题仍然存在。
猜你喜欢
  • 2016-10-14
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多