I edit the Dinner (from the NerdDinner tutorial) and save it, but the Country isn't persisted. Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace NerdDinner.Models
{
public class DinnerFormViewModel
{
private static string[] _countries = new[]{
"USA",
"Bolivia",
"Canada"
};
public Dinner Dinner { get; private set; }
public SelectList Countries { get; private set; }
public DinnerFormViewModel(Dinner dinner)
{
Dinner = dinner;
Countries = new SelectList(_countries, dinner.Country);
}
}
}
Then in my controller I use it like so:
[HttpGet]
public ActionResult Edit(int id)
{
Dinner dinner = dinnerRepository.GetDinner(id);
return View(new DinnerFormViewModel(dinner));
}
[HttpPost]
public ActionResult Edit(int id, FormCollection formValues)
{
Dinner dinner = dinnerRepository.GetDinner(id);
if (TryUpdateModel(dinner))
{
dinnerRepository.Save();
return RedirectToAction("Details", new { id = dinner.DinnerID });
}
return View(new DinnerFormViewModel(dinner));
}
Then, here is the View:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Models.DinnerFormViewModel>" %>
<div class="editor-label">
<%: Html.LabelFor(model => model.Dinner.Country) %>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.Dinner.Country, Model.Countries) %>
<%: Html.ValidationMessageFor(model => model.Dinner.Country) %>
</div>
When trying to edit an existing dinner and change the Country, it doesn't persist the change. Thanks!