[英]NullReferenceException was unhandled asp.net entity framework
我是asp.net mvc的新手,我正在為自己做這個練習。 我從Northwind數據庫創建了一個edmx。 我創建了一個控制器:
public ActionResult Index(int id)
{
var model = new IndexViewModel();
using (var db = new ProductDB())
{
model.Products = from p in db.Products
orderby p.ProductName
select new IndexViewModel.InfoProduct
{
ProductName = p.ProductName,
QuantityPerUnit = p.QuantityPerUnit,
UnitPrice = p.UnitPrice
};
}
return View();
}
...風景:
@model aspTest.Models.IndexViewModel
@{
Layout = null;
}
...
<div> <ul>
@foreach (var p in Model.Products){
<li>@p.ProductName</li>
}
</ul>
</div>
...和ViewModel:
public class IndexViewModel
{
public IEnumerable<InfoProduct> Products { get; set; }
public class InfoProduct
{
public string ProductName { get; set; }
}
}
但是此錯誤繼續出現在此部分:@foreach(Model.Products中的var p){
抱歉,我知道這可能對你們大多數人都不友好。
您在模型中聲明它將與IndexViewModel
類一起使用,如下所示:
@model aspTest.Models.IndexViewModel
但是您沒有向控制器發送任何內容給View:
return View();
嘗試使用:
return View(model);
該錯誤是完全正確的,您正在嘗試迭代不提供的對象( IndexViewModel )的屬性( Products )。
除了不向視圖返回ViewModel並大喊大叫外,還使用return View(model);
您的代碼還有其他問題:
public class InfoProduct
{
public string ProductName { get; set; }
}
您的InfoProduct類僅包含一個Productname,但您還在select子句中分配了Quantity和Price屬性,該屬性不會編譯。
model.Products = from p in db.Products
orderby p.ProductName
select new IndexViewModel.InfoProduct
{
ProductName = p.ProductName,
};
最后,使用.ToList()
數據
public ActionResult Index(int id)
{
var model = new IndexViewModel();
using (var db = new ProductDB())
{
model.Products = (from p in db.Products
orderby p.ProductName
select new IndexViewModel.InfoProduct
{
ProductName = p.ProductName,
}).ToList();
return View(model);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.