2012-07-29 46 views
0

当我将信息发送到MVC中的数据库,我重定向页面,并要求其打印出新存储的数据来看,我得到一个NullReferenceException错误: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"); 
    } 

我不明白为什么它的空...

回答

3
public ActionResult Index() 
    { 
     var customer = db.Customer.ToList(); 
     return View(customer); 
    } 

您从未将customer对象传递给视图。

编辑:也没有包装你的db.SaveChanges();在try/catch可能是危险的,当发生异常。

+0

完美。非常非常感谢你。 – Subby 2012-07-29 03:15:51

相关问题