I am working through Hanselman's tutorial on MVC, and attempting to use a view model in the Create and Edit views so as to fill in a pulldown menu. In this we are directed to create a table Dinner
, with columns including Title
and Country
and the related classes, and then a ViewModel containing a dinner
object and a SelectList
for a pull-down menu thus:-
public class DinnerFormViewModel {
public Dinner Dinner { get; private set; }
public SelectList Countries { get; private set; }
public DinnerFormViewModel (Dinner dinner) {
Dinner = dinner;
Countries = new SelectList(...code to create list of countries..., dinner.Country);
}
}
This I use to create Edit and Create methods in the controller. The Edit method looks like this:-
public ActionResult Edit(int id, FormCollection formValues) {
Dinner dinner = dinnerRepository.GetDinner(id);
try {
UpdateModel(dinner);
dinnerRepository.Save();
return RedirectToAction("Details", new { id = dinner.DinnerId });
}
catch { ...etc... }
}
and the code generated in the view looks like this:-
<div class="editor-field">
<%: Html.EditorFor(model => model.Dinner.Title) %>
<%: Html.ValidationMessageFor(model => model.Dinner.Title) %>
</div>
<div class="editor-field">
<%: Html.DropDownList("Country", Model.Countries) %>
<%: Html.ValidationMessage("Country", "*") %>
</div>
So far, so good. But when it comes to the Create method it starts to get a bit strange. While the code in the view is essentially identical, when I invoke the UpdateModel
method to fill in the dinner
object, the only field that is filled in is the Country
, from the pull-down menu; when I try it with the DinnerFormViewModel
, the Country
in the Dinner
is left null
, but all the other fields are filled in. So the Create method looks like this:-
public ActionResult Create(FormCollection formValues) {
Dinner dinner = new Dinner();
DinnerFormViewModel dinnerFormViewModel = new DinnerFormViewModel(new Dinner());
try {
UpdateModel(dinnerFormViewModel);
UpdateModel(dinner);
dinnerFormViewModel.Dinner.Country = dinner.Country;
dinnerRepository.Add(dinnerFormViewModel.Dinner);
dinnerRepository.Save();
return RedirectToAction("Details", new { id = dinnerFormViewModel.Dinner.DinnerId });
}
catch {...etc...}
}
While this works, it doesn't to me look like it is the way I should be writing this code. Is it right, or if it isn't, what should I be doing? (It is a thousand pities that the example given in the tutorial doesn't compile.)