【问题标题】:Exception Details: System.NullReferenceException: Object reference not set to an instance of an object异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例
【发布时间】:2013-06-15 21:09:13
【问题描述】:

我见过很多有这样问题的主题,但找不到我的。在此错误之后,它指定了一个来源:

    @{
Line 4:      ViewBag.Title = "Edit product: " + @Model.Name;
Line 5:      Layout = "~/Views/Shared/_MasterLayout.cshtml";
Line 6:  
}

它发生在我从视图中单击我的产品名称后

@Html.ActionLink(item.Name, "Edit", new { item.ProductID })

链接变成了

http://localhost:31363/Master/Edit?ProductID=1

但是,如果我手动将链接编辑为

,我将无法看到我的视图
http://localhost:31363/Master/Edit/1

它有效。那么,我应该如何解决才能使其以第一种方式或在第二种方式中自动工作?我现在没有任何特殊的路由,它是 Mvc4 应用程序附带的默认路由。

【问题讨论】:

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


    【解决方案1】:

    这应该可以解决问题:

    @Html.ActionLink(item.Name, "Edit", new { id = item.ProductID })
    

    说明

    在您的代码中,您正在创建一个带有 ProductID 参数的链接,因为

    @Html.ActionLink(item.Name, "Edit", new { item.ProductID })
    

    等于:

    @Html.ActionLink(item.Name, "Edit", new { ProductID = item.ProductID })
    

    由于默认路由中没有名为 ProductID 的参数,因此将其添加到查询字符串中。此外,您的 Edit 操作可能有一个名为 id 的整数参数,如下所示:

    public ActionResult Edit(int id)
    

    由于此参数不是可选的或可为空的,因此无法将请求映射到此操作并且您会收到错误消息。所以参数名称很重要,因为 ASP.NET MVC 无法自行判断。

    【讨论】:

    • 没想到,竟然这么简单。非常感谢!!
    猜你喜欢
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    相关资源
    最近更新 更多