Overview:
I am trying to use a ViewModel that has a property that is a model class that I am trying to edit. I saw how an editable form works using MVC forest editing forms when editing a model directly, however I am trying to use a ViewModel that contains an editable model. Everything works, except for saving the field displayed in DropDownList.
Explanation:
I tried to use the forest functions for MVC 3 to create an edit form for the model. In the MVC Music Store tutorial, this is done for the edit page Album, in StoreManagerController. Inside this page, they have two slopes for the genre and artist. Each one looks something like this: "
<div class="editor-label">
@Html.LabelFor(model => model.GenreId, "Genre")
</div>
<div class="editor-field">
@Html.DropDownList("GenreId", String.Empty)
@Html.ValidationMessageFor(model => model.GenreId)
</div>
As far as I can tell, they have their own options populated in the controller using the ViewBag.
ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);
Work with the model directly
In my code, I managed to do the same with an object that is stored in DB through the Entity Framework.
Model
public class Season
{
public int SeasonId { get; set; }
public int ClubId { get; set; }
public Club Club { get; set; }
}
Code in the controller
ViewBag.ClubId = new SelectList(clubs, "ClubId", "Name", season.ClubId);
View
<div class="editor-label">
@Html.LabelFor(model => model.ClubId, "Club")
</div>
<div class="editor-field">
@Html.DropDownList("ClubId", String.Empty)
@Html.ValidationMessageFor(model => model.ClubId)
</div>
This works great.
Working with a viewing model
, , , , .
() , .
ViewModel
public class EditSeasonViewModel
{
public string PlayerName {get; set;}
public string SummaryText {get; set;}
public int PlayerId {get; set;}
public Season season {get; set;}
}
, , HttpGet HttpPost ViewModel, , ViewModel, "EditorFor" , model.season.MyProperty.
ViewBag.ClubId = new SelectList(clubs, "ClubId", "Name", seasonVM.season.ClubId);
<div class="editor-label">
@Html.LabelFor(model => model.season.ClubId, "Club")
</div>
<div class="editor-field">
@Html.DropDownList("ClubId", String.Empty)
@Html.ValidationMessageFor(model => model.season.ClubId)
</div>
HttpPost , ClubId, DropDropList.
DropDownList , , .
:
, ClubId EditSeasonViewModel?
, ViewBag.ClubId HttpGet DropDownList , HttpPost?