Cal*_*ski 0 c# asp.net asp.net-mvc entity-framework asp.net-mvc-4
我是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();
}
Run Code Online (Sandbox Code Playgroud)
...风景:
@model aspTest.Models.IndexViewModel
@{
Layout = null;
}
...
<div> <ul>
@foreach (var p in Model.Products){
<li>@p.ProductName</li>
}
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
...和ViewModel:
public class IndexViewModel
{
public IEnumerable<InfoProduct> Products { get; set; }
public class InfoProduct
{
public string ProductName { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
但是这个错误继续出现在这个部分:@foreach(Model.Products中的var p){
对不起,我知道这对大多数人来说可能是愚蠢的.
您在模型中声明它将与IndexViewModel该类一起使用:
@model aspTest.Models.IndexViewModel
Run Code Online (Sandbox Code Playgroud)
但是您没有向Controller发送任何视图,因为:
return View();
Run Code Online (Sandbox Code Playgroud)
尝试使用:
return View(model);
Run Code Online (Sandbox Code Playgroud)
错误是完全正确的,您正在尝试迭代您未提供的对象(IndexViewModel)的属性(Products).
| 归档时间: |
|
| 查看次数: |
319 次 |
| 最近记录: |