开发者

Why pass data context class through View() instead of ViewBag?

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?


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 the ViewBag), but IEnumerable<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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜