2012-07-29 48 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

相關問題