为什么通过 View() 而不是 ViewBag 传递数据上下文类?
如果我有一个带有索引页的控制器:
@model IEnumerable<MvcMovie.Models.Movie>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table>
<tr>
<th>
Title
</th>
....
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
....
</tr>
}
</table>
使用 @model IEnumerable
有什么优势?为什么我不能在控制器中定义 ViewBag.Movies
并在索引页中使用它?
If I have a Controller, with an Index page:
@model IEnumerable<MvcMovie.Models.Movie>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table>
<tr>
<th>
Title
</th>
....
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
....
</tr>
}
</table>
Whats the advantage of using @model IEnumerable<Movie>
? Why couldn't I just define ViewBag.Movies
in the Controller and use that in the index page?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
@model IEnumerable
的优点是预先说明清楚 - 该视图旨在显示(一个)IEnumerable
。它可能会使用一些附加信息(这些信息将存储在ViewBag
中),但IEnumerable
才是它要显示的内容。这是概念上的原因,这和MVC设计模式的概念有很大关系。当然,正如 @Tridus 所说,还有技术原因。The advantage of using
@model IEnumerable<Movie>
is the clarity of saying right upfront - this view is meant to display (an)IEnumerable<Movie>
. It may use some additional information (which will be stored in theViewBag
), butIEnumerable<Movie>
is what it's meant to display. That's conceptually the reason, which has a lot to do with the concept of the MVC design pattern. And of course there are the technical reasons as @Tridus said.严格来说,你可以。但是,如果您将其他内容传递给视图,您将不会受益于智能感知或直接的“这是错误的类型”错误。如果您在编译时启用编译视图,您也不会捕获错误(尽管默认情况下这是关闭的,因此好处不大)。
Strictly speaking, you could. But you're not going to get the benefit of Intellisense or a straightforward "this is the wrong type" error if you pass in something else to the View. You also won't get errors caught if you enable compiling your views at compile time (though that's off by default so it's less of a benefit).