将ASP.NET MVC与实体框架一起使用
我使用viewdata来显示不属于页面模型的信息。表单包含强类型模型,而客户信息显示在表单的顶部。我可以在提交表单之前看到显示的信息,所以我知道它不是空的,即使这是为什么我在发送表单时会收到错误,因为它不是表单的一部分?
导致错误的代码
@model Sondage_Epicier.Models.Sondage_Vendeur
@{
Sondage_Epicier.Models.CLIENT cust = (Sondage_Epicier.Models.CLIENT)
ViewData["Customer"];
}
<div id="sondage">
<div class="subForm" style="margin-bottom: -20px;">
<p class="info">@Resources.numClient2 @cust.NO_CLIENT</p><br />
<p class="info">@Resources.nom @cust.NOM</p><br />
<p class="info">@Resources.address @cust.ADR_1 , @cust.VILLE</p>
</div>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true, "", new { @class = "" })
@Html.HiddenFor(model => model.SondageID)
@Html.HiddenFor(model => model.Date_Envoye)
@Html.AntiForgeryToken()
我为法语中的SQL堆栈道歉,要明白@cust导致的问题不是@Resources
答案 0 :(得分:0)
您收到错误是因为cust
对象为NULL。您正在尝试访问NULL对象上的属性并将着名的对象引用未设置为对象的实例错误
为什么cust
对象为NULL?您正在通过阅读cust
设置ViewData["Customer"]
变量的值。如果ViewData["Customer"]
未设置为有效CLIENT
实例,该怎么办?您提到在提交表单时收到错误。这通常在您提交表单时发生,并且在您的http post action方法中,您将返回到同一视图而不重新加载ViewData / ViewBag字典项。
因此解决方案是在返回使用它的视图之前将客户对象重新加载到ViewData字典。
[HttpPost]
public ActionResult Save(SomeViewModel model)
{
//your existing code
// here i am creating a new object and assigning it.
// Replace with your code which you use in the GET action
var customer = new Sondage_Epicier.Models.CLIENT();
ViewData["Customer"] =customer;
return View();
}
请记住, Http是无国籍的。