Академический Документы
Профессиональный Документы
Культура Документы
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 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
[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 athttp://automapper.codeplex.com/ and the source code is hosted
at http://code.google.com/p/automapperhome.
What is a Model
Domain logic handles the data that is passed between the database and the UI.
As an example, in an inventory system, the model keeps track of the items in storage
and the logic to determine whether an item is in stock.
In addition, the model would be the part of the application that updates the
database,when an item is sold and shipped out of the warehouse.
Often, the model also stores and retrieves model state in a database.
What is a ViewModel
Allow you to shape multiple entities from one or more data models or sources into a
single object.
Optimized for consumption and rendering by the view.
It shows below image
2. This allows you to validate your ViewModel differently than your domain model for
attribute-based validation scenarios
4. The use of a ViewModel can make the interaction between model and view more simple
1. In a folder called ViewModels that resides in the root of the project. (small applications)
2. The View should direct the properties of the ViewModel, this way it fits better for
rendering
and maintenance
3. Use a Mapper when ViewModels become Complex (i.e. How to Use ValueInjecter ? )
Asp.net MVC 5,C# and Visual Studio 2013 express has been used.
This is a simple application with product category drop down list, product name text
box and Save button.
Domain Models
Product.cs
public class Product
{
ProductCategory.cs
public class ProductCategory
{
public int Id { get; set; }
public string CategoryName { get; set; }
ViewModel
ProductViewModel.cs
[Required(ErrorMessage = "required")]
public string ProductName { get; set; }
[DisplayName("Product Category")]
public virtual ICollection<ProductCategory> ProductCategories { get; set; }
}
/// <summary>
/// to save entered data
/// </summary>
[HttpPost]
public ActionResult AddProduct(ProductViewModel productViewModel) //save entered data
{
//instantiate the product repository
var productRepository = new ProductRepository();
ue);
{
ProductName = productViewModel.ProductName,
ProductCategory = prodcutCategory,
};
return RedirectToAction("AddProduct");
}
else
{
//when validation failed return viewmodel back to UI (View)
return View(productViewModel);
}
}
View
AddProduct.cshtml
<div class="boxedForm">
@using (Html.BeginForm())
{
Html.EnableClientValidation(true);
<ul style="margin-top:50px;">
<li style="width: 370px">
@Html.LabelFor(m => m.ProductCategories)
@Html.DropDownListFor(m => m.SelectedValue,
new SelectList(Model.ProductCategories, "Id","CategoryName"), "-Please select a category-")
@Html.ValidationMessageFor(m => m.ProductCategory.Id)
</li>
<li style="width: 370px;margin-top:10px;">
@Html.LabelFor(m => m.ProductName)
@Html.EditorFor(m => m.ProductName)
@Html.ValidationMessageFor(m => m.ProductName)
</li>
</ul>
<div class="action">
<button class="actionButton" type="submit">
<span>Save</span>
</button>
</div>
}
</div>
/// <summary>
/// to get all product categories
/// </summary>
/// <returns></returns>
/// <summary>
/// to Get All Product Categories mock datas
/// </summary>
private List<ProductCategory> GetAllProductCategoriesMockDatas()
{
var productCategoryList = new List<ProductCategory>();
productCategoryList.Add(new ProductCategory
{
Id = 1,
CategoryName = "Foods",
});
productCategoryList.Add(new ProductCategory
{
Id = 2,
CategoryName = "Toys",
});
productCategoryList.Add(new ProductCategory
{
Id = 3,
CategoryName = "Mobile Phones",
});
return productCategoryList;
}