EDIT: I made something much better to fill and read data from a view using ViewModels, called it ValueInjecter. http://valueinjecter.codeplex.com/
it is used by http://prodinner.codeplex.com – an ASP.net MVC sample application
you can see the best way of using ViewModels in prodinner
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
That’s the old stuff, don’t use it:
I made a ViewModel pattern for editing stuff in asp.net mvc
this pattern is useful when you have to make a form for editing an entity and you have to put on the form some drop-downs for the user to choose some values
public class OrganisationBadViewModel
{
//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; }
...
}
There are couple of things that bother me.
The terminology. ViewModel is this case is a simple view data that is populated and later consumed by controller. View knows nothing about controller as ASP.NET MVC infrastructure is responsible for selecting controllers and appropriate actions. Controller handles user interaction. I think it looks more like Passive View than ViewModel (I assume that by ViewModel you mean Model-View-ViewModel pattern).
The details. The controller that populates view data is not supposed to know the details of how the view is implemented. However OrganisationViewModel.Country discloses unnecessary details (SelectListItem is pure view implementation detail). Thus making controller dependent on view implementation details. I think it should be changed to avoid it. Consider using some object that will hold the data for a country.
Hope this helps.