Entity
Entity

Reputation: 8222

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?

Upvotes: 0

Views: 1332

Answers (2)

Oren A
Oren A

Reputation: 5900

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.

Upvotes: 2

Tridus
Tridus

Reputation: 5081

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).

Upvotes: 2

Related Questions