MVC 4 NullReferenceException 当我从控制器重定向时查看

MVC 4 NullReferenceException on View When I Redirect from Controller

提问人:Amit 提问时间:5/4/2014 最后编辑:GlorfindelAmit 更新时间:9/16/2019 访问量:773

问:

当我从控制器重定向到视图时,我收到 NullReferenceException。我尝试调试,但调试器在进入视图并引发异常时停止。

这是我在 View 中的代码。

@model MvcApplication2.Models.Product

@{
    ViewBag.Title = "ProductDetails"; //NullReferenceException Here. If I comment this line, then page doesn't even load, and I get "No Souce found".
}

<div class="span9">
    <ul class="breadcrumb">
    <li><a [email protected]("Index", "Home") >Home</a> <span class="divider">/</span></li>
    <!--<li><a href= >Products</a> <span class="divider">/</span></li>-->
    <li class="active">product Details</li>
    </ul>
</div>

我在 Controller 中的代码,它重定向到此视图。

 public ActionResult ProductDetails(int productID=0)
        {
            //read product from the database
            Product product = (from item in shoppingDb.products where item.ID ==     productID select item).SingleOrDefault();
            Session["CurrentUrl"] = "/Products/ProductDetails?productID=" + productID;
            //Session["ReturnProductsUrl"] = Request.Path.ToString();
            //ViewBag.Comment = "this is test";
            return View(product);
        }

我通过将 productID=1 作为 URL 中的参数传递来测试此代码。

这是我的数据库快照,显示我有一个 ID = 1 的条目。

DatabaseSnapshot

以下是几件事: 1.我正在将一个对象从控制器传递到视图。 2.如果我注释掉ViewBag.Title行,那么我也会得到同样的异常 3. 我通过调试观察到控制器中的产品对象不为空。 4. 我尝试在操作中向 ViewBag 添加一些数据,但结果仍然相同。

这段代码工作了好几天,突然开始出现这个异常。不知道问题出在哪里..我到处搜索,都没有得到正确的答案。

C# ASP.NET-MVC-4 Razor NullReferenceException

评论

0赞 ℍ ℍ 5/4/2014
该评论表明,在没有 ViewBag 系列的情况下会发生其他事情。
1赞 5/4/2014
你试过扩展方法吗?ViewBag 不会导致问题.FirstOrDefault()
0赞 John Saunders 5/4/2014
几乎所有的情况都是一样的。有关一些提示,请参阅“什么是 .NET 中的 NullReferenceException?”NullReferenceException
0赞 ℍ ℍ 5/4/2014
@JohnSaunders - 这更像是一个“调试 nullref 失败”的问题。涉及剃刀,所以不是工厂的骗局。
0赞 John Saunders 5/4/2014
@HenkHolterman:此方案的简化版本可能是对链接问题的一个很好的补充。

答: 暂无答案