View Model pattern and AutoMapper in ASP.NET MVC Applications

In real world ASP.NET MVC applications, we have to use model objects specially designed for our ASP.NET MVC views. Domain objects are designed for the needs for domain model and it is representing the domain of our applications. On the other hand, View Model objects designed for our needs for views.

The below is the domain model of our demo

 



We have a Contact domain entity that has a association with Contact Group. While we creating a new Contact, we have to specify that in which contactgroup belongs with the new contact.


The below is the user interface for creating a new contact

 



The above new contact UI has the form fields for representing the Contact entity and a GroupId field for representing the contact group.


The below is the class for Contact View Model

 

public class ContactViewModel

{

public int Id

{

    get;

    set;

}

[Required(ErrorMessage = "FirstName Required")]

[StringLength(25, ErrorMessage = "Must be less than 25 characters")]

public string FirstName

{

    get;

    set;

}

[Required(ErrorMessage = "LasttName Required")]

[StringLength(25, ErrorMessage = "Must be less than 25 characters")]

public string LastName

{

    get;

    set;

}      

 

[Required(ErrorMessage = "Email Required")]

[RegularExpression("^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$", ErrorMessage = "Not a valid email")]

public string EMail

{

    get;

    set;

}

[Required(ErrorMessage = "Phone Required")]

public string Phone

{

    get;

    set;

}

public string Address

{

    get;

    set;

}

[Required(ErrorMessage = "GroupId Required")]     

public int GroupId

{

    get;

    set;

}

public IEnumerable<SelectListItem> ContactGroup

{

    get;

    set;

}

 

}

 

Our Contact View Model is designed for the purpose of View template and contains the all validation rules. It has properties for mapping values to Contact entity and a GroupId property for taking Id value from ContactGroup drop-down. And also providing a property ContactGroup for binding values to ContactGroup drop-down.

 The below code is Action method for Create Contact HttpGet request where we are creating an instance of Contact View Model and sets the Contactgroup property for binding values to drop-down list.

/HttpGet for the Create Contact

public ActionResult Create() {

    var viewModel = new ContactViewModel();

    var groups = contactRepository.ListGroups();

    viewModel.ContactGroup = groups.ToSelectListItems(-1);

    if (groups.Count<ContactGroup>() == 0)

        return RedirectToAction("Index", "Group");

    return View("Create", viewModel);

}

 

  The below code is Action method for Create Contact HttpPost request.

[HttpPost]

public ActionResult Create(ContactViewModel contactToCreate) {

if (ModelState.IsValid) {

 

    Contact newContact = new Contact();

    AutoMapper.Mapper.Map(contactToCreate, newContact);

    contactRepository.CreateContact(contactToCreate.GroupId, newContact);   

 }

}

 

In the above action method, our model binder is the ContactViewModel and we have to map values of ContactViewModel object to Domain model object Contact for the persistance purpose. In ASP.NET MVC applications, you have to map values between view model objects and domain model objects in many situations. In such scenarios, you can use AutoMapper for mapping values between objects to objects.In our code we copy values from our View model object ContactViewModel  to domain model object Contact. AutoMapper is a convention based object to object mapper framework developed by Jimmy Bogard. 

 A mapping configuration is a one time task and the below code setting map configuarion between our ContactViewModel and Contact.

Mapper.CreateMap<ContactViewModel,Contact>();

The below code from the Create method of HttpPost action, copy values of ContactViewModel object to Contact object

AutoMapper.Mapper.Map(contactToCreate, newContact);

 Check the Flattening for mapping to take a complex object model and flatten it to a simpler model. AutoMapper is available at http://automapper.codeplex.com/ and the source code is hosted at http://code.google.com/p/automapperhome.

Published Monday, February 01, 2010 3:01 AM by shiju
Filed under: ,

Comments

# View Model pattern and AutoMapper in ASP.NET MVC Applications

Monday, February 01, 2010 6:42 AM by DotNetKicks.com

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# View Model pattern and AutoMapper in ASP.NET MVC Applications - Shiju Varghese's Blog

Monday, February 01, 2010 11:26 AM by 9eFish

9efish.感谢你的文章 - Trackback from 9eFish

# Social comments and analytics for this post

Monday, February 01, 2010 11:35 AM by uberVU - social comments

This post was mentioned on Twitter by jrguay: #ASPNET #Weblog: View Model pattern and AutoMapper in ASP.NET MVC Applications: In real world ASP.NET MVC applicat... http://bit.ly/aIcNcL

# View Model pattern and AutoMapper in ASP.NET MVC Applications - Shiju Varghese's Blog

Tuesday, February 02, 2010 1:48 AM by DotNetShoutout

Thank you for submitting this cool story - Trackback from DotNetShoutout

# The Morning Brew - Chris Alcock &raquo; The Morning Brew #530

Tuesday, February 02, 2010 3:41 AM by The Morning Brew - Chris Alcock » The Morning Brew #530

Pingback from  The Morning Brew - Chris Alcock  &raquo; The Morning Brew #530

# Performance: Using dynamic code to copy property values of two objects | I love .NET!

Pingback from  Performance: Using dynamic code to copy property values of two objects | I love .NET!

# ASP.NET MVC View Model object using C# 4 dynamic and ExpandoObject

Wednesday, February 03, 2010 1:07 AM by Shiju Varghese's Blog

In my last post , I have explained the use of View Model objects in ASP.NET MVC applications. In this

# Twitter Trackbacks for View Model pattern and AutoMapper in ASP.NET MVC Applications - Shiju Varghese's Blog [asp.net] on Topsy.com

Pingback from  Twitter Trackbacks for                 View Model pattern and AutoMapper in ASP.NET MVC Applications - Shiju Varghese's Blog         [asp.net]        on Topsy.com

# re: View Model pattern and AutoMapper in ASP.NET MVC Applications

Thursday, February 25, 2010 10:07 AM by Ben

Using <%= Html.EditorForModel() %> doesn't create the drop down list automatically. Is that by design?

# re: View Model pattern and AutoMapper in ASP.NET MVC Applications

Thursday, February 25, 2010 11:10 PM by shiju

@Ben It will not create drop down list automatically and will be working with simple types by default.

# ASP.NET MVC ModelCopier

Tuesday, April 27, 2010 11:41 PM by Shiju Varghese's Blog

In my earlier post ViewModel patten and AutoMapper in ASP.NET MVC application , We have discussed the

# Performance: Using dynamic code to copy property values of two objects | OOP - Object Oriented Programing

Pingback from  Performance: Using dynamic code to copy property values of two objects | OOP - Object Oriented Programing

# ASP.NET MVC ModelCopier | OOP - Object Oriented Programing

Pingback from  ASP.NET MVC ModelCopier | OOP - Object Oriented Programing

# re: View Model pattern and AutoMapper in ASP.NET MVC Applications

Friday, June 11, 2010 3:49 AM by Omu

ValueInjecter is much better for this purpose, and it has sample asp.net-mvc application in the download where it is demonstrated how you can map entities to/from viewmodels and formcollection/request to entities and much more

# re: View Model pattern and AutoMapper in ASP.NET MVC Applications

Friday, June 11, 2010 3:49 PM by Yonah Wahrhaftig

I realize that this post is a little old by now but maybe you are still monitoring comments since comments are still open.

What do you do about your dropdownlist in the event the model state is not valid. Do you have to repopulate again from the repository? Is there a way to have the ModelBinder bind the IEnumerable<SelectListItem> back to the model?

# re: View Model pattern and AutoMapper in ASP.NET MVC Applications

Wednesday, April 27, 2011 4:59 AM by katie D

hello, when you want to simply display the group's name, how can you achieve this from the contact's groupID?

thanks,

# re: View Model pattern and AutoMapper in ASP.NET MVC Applications

Wednesday, July 20, 2011 5:11 AM by darshanthacker

great post with example.

# how can get data from another Table - Programmers Goodies

Pingback from  how can get data from another Table - Programmers Goodies

# re: View Model pattern and AutoMapper in ASP.NET MVC Applications

Tuesday, August 16, 2011 6:51 PM by byuan

I cannot find the code to be downloaded?

# re: View Model pattern and AutoMapper in ASP.NET MVC Applications

Wednesday, August 17, 2011 1:30 PM by byuan

Can I see the code of contactRepository so that I will have better understanding of the  method here. Thanks.

# re: View Model pattern and AutoMapper in ASP.NET MVC Applications

Wednesday, August 17, 2011 2:07 PM by byuan

Or can you post the entire code if the code download is not available?

# ASP.NET MVC3 Automapper Viewmodel/Model View validation - Programmers Goodies

Pingback from  ASP.NET MVC3 Automapper Viewmodel/Model View validation - Programmers Goodies

# re: View Model pattern and AutoMapper in ASP.NET MVC Applications

Sunday, March 11, 2012 4:01 AM by Varun Maggo

Very helpful post!

# ASP.NET MVC????????????????????? | Apworks.ORG

Monday, February 11, 2013 6:57 AM by ASP.NET MVC????????????????????? | Apworks.ORG

Pingback from  ASP.NET MVC????????????????????? | Apworks.ORG

Leave a Comment

(required) 
(required) 
(optional)
(required)