menrfa
menrfa

Reputation: 1667

Under-hood explanation required for asp.net MVC tutorial

refer to asp.net MVC tutorial: http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/examining-the-edit-methods-and-edit-view

regarding the autogenerated Views\Movies\SearchIndex.cshtml

Question 1:

<p>
@Html.ActionLink("Create New", "Create")

@using (Html.BeginForm())
{
    <p>
        Genre: @Html.DropDownList("movieGenre", "All")
        Title: @Html.TextBox("SearchString", "Movies", FormMethod.Get)
        <input type="submit" value="Filter" />
    </p>
}
</p>

how does movieGenre refer to @ViewBag.movieGenre, which is obviously defined in Controllers/MoviesController.cs

Question 2:

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Title)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.ReleaseDate)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Genre)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Price)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
        @Html.ActionLink("Details", "Details", new { id=item.ID }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.ID })
    </td>
</tr>
}

where is modelItem defined? VS2010 shows me modelItem is

IEnumerable <MvcMovie.Model.Movie>

Thanks.

Upvotes: 1

Views: 657

Answers (1)

Ant P
Ant P

Reputation: 25221

Looks like you've already answered your second question, so I'll just answer your first:

The Html.DropDownList helper will bind itself to ViewData by default if no data is provided to it. ViewBag is simply a dynamic wrapper around the ViewData dictionary, so when you set ViewBag.movieGenre = new SelectList() you are effectively setting ViewData["movieGenre"] = new SelectList().

Now that you have this SelectList in your ViewData, the following will automatically bind this to the dropdown:

@Html.DropDownList("movieGenre")

This implicit binding isn't very well documented. See here for more information:

http://weblogs.asp.net/pjohnson/archive/2012/10/26/mvc-s-html-dropdownlist-and-quot-there-is-no-viewdata-item-of-type-ienumerable-lt-selectlistitem-gt-that-has-the-key.aspx

Upvotes: 1

Related Questions