ASP.NET MVC ViewModel Pattern
- by Omu
EDIT: I made something much better to fill and read data from a view using ViewModels, called it ValueInjecter. http://valueinjecter.codeplex.com/documentation
using the ViewModel to store the mapping logic was not such a good idea because there was repetition and SRP violation, but now with the ValueInjecter I have clean ViewModels and dry mapping code
I made a ViewModel pattern for editing stuff in asp.net mvc
this pattern is usefull when you have to make a form for editing an entity and you have to put on the form some dropdowns for the user to choose some values
public class OrganisationViewModel
{
//paramterless constructor required, cuz we are gonna get an OrganisationViewModel object from the form in the post save method
public OrganisationViewModel() : this(new Organisation()) {}
public OrganisationViewModel(Organisation o)
{
Organisation = o;
Country = new SelectList(LookupFacade.Country.GetAll(), "ID", "Description", CountryKey);
}
//that's the Type for whom i create the viewmodel
public Organisation Organisation { get; set; }
#region DropDowns
//for each dropdown i have a int? Key that stores the selected value
public IEnumerable<SelectListItem> Country { get; set; }
public int? CountryKey
{
get
{
if (Organisation.Country != null)
{
return Organisation.Country.ID;
}
return null;
}
set
{
if (value.HasValue)
{
Organisation.Country = LookupFacade.Country.Get(value.Value);
}
}
}
#endregion
}
and that's how i use it
public ViewResult Edit(int id)
{
var model = new OrganisationViewModel(organisationRepository.Get(id));
return View(model);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(OrganisationViewModel model)
{
organisationRepository.SaveOrUpdate(model.Organisation);
return RedirectToAction("Index");
}
and the markup
<p>
<label for="Name">
Name:</label>
<%= Html.Hidden("Organisation.ID", Model.Organisation.ID)%>
<%= Html.TextBox("Organisation.Name", Model.Organisation.Name)%>
<%= Html.ValidationMessage("Organisation.Name", "*")%>
</p>
<p>
...
<label for="CountryKey">
Country:</label>
<%= Html.DropDownList("CountryKey", Model.Country, "please select") %>
<%= Html.ValidationMessage("CountryKey", "*") %>
</p>
so tell me what you think about it