【发布时间】:2012-07-20 15:50:11
【问题描述】:
我正在学习 C# ASP.NET MVC 3 中的 ViewModel,但我一直无法在我的视图中显示来自 ViewModel 的数据。
模型:
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
public class Book
{
public int Id { get; set; }
public int AuthorId { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
}
在我的索引视图中,我想显示作者和书籍的一般列表。我为此制作了一个 ViewModel:
public class BookIndexViewModel
{
public List<Book> Books { get; set; }
public List<Author> Authors { get; set; }
}
这是来自控制器的 Index() 操作方法:
public ViewResult Index()
{
BookIndexViewModel viewModel = new BookIndexViewModel();
viewModel.Authors = db.Authors.ToList();
// leaving Books empty for now
return View(viewModel);
}
我有一个强类型索引视图,我想在其中显示作者列表:
@model IEnumerable<NewBookStore.ViewModels.BookIndexViewModel>
@foreach (var author in Model.Authors) {
<tr>
<td>
@author.Name
</td>
</tr>
}
Model.Authors 部分不起作用。当我键入模型时。并等待 IntelliSense 显示作者,它未列出。错误描述为:
“System.Collections.Generic.IEnumerable”不包含“Authors”的定义,并且找不到接受“System.Collections.Generic.IEnumerable”类型的第一个参数的扩展方法“Authors”(您是否缺少using 指令还是程序集引用?)
【问题讨论】:
-
视图中的模型不应该是 IEnumerable。您正在发送一个模型,其中包含 2 个列表。您没有发送视图模型列表。
标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-viewmodel