当我向MVC中的数据库发送信息并重定向页面并调用打印新存储的数据的视图时,我得到了一个NullReferenceException错误:
“对象引用未设置为对象的实例。”
显然,我的模型为空:
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.CustomerID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}这是我的控制器:
public ActionResult Index()
{
var customer = db.Customer.ToList();
return View();
}它通过以下方式调用:
[HttpPost]
public ActionResult Create(CustomerModel customer)
{
db.Customer.Add(customer);
db.SaveChanges();
return RedirectToAction("Index");
}我不明白为什么它是空的……
发布于 2012-07-29 10:47:47
public ActionResult Index()
{
var customer = db.Customer.ToList();
return View(customer);
}您永远不会将customer对象传递给视图。
编辑:当发生异常时,不将db.SaveChanges();包装在try/catch中也是危险的。
https://stackoverflow.com/questions/11706246
复制相似问题