So lets say I have an object
class MyItem
{
public string Name {get; set;}
public string Description {get; set;}
}
I want to create a ViewModel
class MyItemViewModel
{
public string Name {get; set;}
public string Description {get; set;}
public string Username {get; set;}
}
I would like to on the controller get an object of type MyItem and automatically populate the ViewModel. With the values contained within MyItem (ie if it has a property called Name, automatically fill it out).
What I am trying to avoid is a list of Model.Name = Item.Name rows. MyItemViewModel will also have different attributes and display values so I cannot simply embed MyItem within the View Model.
Is there a clean programmatical way of duplicating attributes of the same name and type between objects or am I stuck by doing it by hand?
You could use AutoMapper for this task. I am using it in all projects to map between my domain models and view models.
You simply define a mapping in your
Application_Start:and then perform the mapping:
and you could write a custom action filter which overrides the OnActionExecuted method and substitues the model that was passed to the view with the corresponding view model:
This makes your controller actions pretty simple.
AutoMapper has another very useful method which could be used in your POST actions when you want to update something:
Imagine for example that you had a User domain model containing properties like Username, Password and IsAdmin and that you have a form allowing the user for changing his username and password but absolutely not changing the IsAdmin property. So you would have a view model containing the Username and Password properties bound to an html form in the view and using this technique you will only update those 2 properties, leaving the IsAdmin property untouched.
AutoMapper also works with collections. Once you have defined a mapping between the simple types:
you don’t need to do anything special when mapping between collections:
So wait no more, type the following command in your NuGet console and enjoy the show: