Sunday, January 26, 2014

ASP.NET MVC: ASP.NET MVC View Model Patterns

Since MVC has been released I have observed much confusion about how best to construct view models. Sometimes this confusion is not without good reason since there does not seem to be a ton of information out there on best practice recommendations.  Additionally, there is not a “one size fits all” solution that acts as the silver bullet. In this post, I’ll describe a few of the main patterns that have emerged and the pros/cons of each. It is important to note that many of these patterns have emerged from people solving real-world issues.
Another key point to recognize is that the question of how best to construct view models is *not* unique to the MVC framework.  The fact is that even in traditional ASP.NET web forms you have the same issues.  The difference is that historically developers haven’t always dealt with it directly in web forms – instead what often happens is that the code-behind files end up as monolithic dumping grounds for code that has no separation of concerns whatsoever and is wiring up view models, performing presentation logic, performing business logic, data access code, and who knows what else.  MVC at least facilitates the developer taking a closer look at how to more elegantly implement Separation of Concerns.
Pattern 1 – Domain model object used directly as the view model
Consider a domain model that looks like this:
   1:  public class Motorcycle
   2:  {
   3:      public string Make { get; set; }
   4:      public string Model { get; set; }
   5:      public int Year { get; set; }
   6:      public string VIN { get; set; }
   7:  }
When we pass this into the view, it of course allows us to write simple HTML helpers in the style of our choosing:
   1:  <%=Html.TextBox("Make") %>
   2:  <%=Html.TextBoxFor(m => m.Make) %>
And of course with default model binding we are able to pass that back to the controller when the form is posted:
   1:  public ActionResult Save(Motorcycle motorcycle)
While this first pattern is simple and clean and elegant, it breaks down fairly quickly for anything but the most trivial views. We are binding directly to our domain model in this instance – this often is not sufficient for fully displaying a view.
Pattern 2 – Dedicated view model that *contains* the domain model object
Staying with the Motorcycle example above, a much more real-world example is that our view needs more than just a Motorcycle object to display properly.  For example, the Make and Model will probably be populated from drop down lists. Therefore, a common pattern is to introduce a view model that acts as a container for all objects that our view requires in order to render properly:
   1:  public class MotorcycleViewModel
   2:  {
   3:      public Motorcycle Motorcycle { get; set; }
   4:      public SelectList MakeList { get; set; }
   5:      public SelectList ModelList { get; set; }
   6:  }
In this instance, the controller is typically responsible for making sure MotorcycleViewModel is correctly populated from the appropriate data in the repositories (e.g., getting the Motorcycle from the database, getting the collections of Makes/Models from the database).  Our Html Helpers change slightly because they refer to Motorcycle.Make rather than Make directly:
   1:  <%=Html.DropDownListFor(m => m.Motorcycle.Make, Model.MakeList) %>
When the form is posted, we are still able to have a strongly-typed Save() method:
   1:  public ActionResult Save([Bind(Prefix = "Motorcycle")]Motorcycle motorcycle)
Note that in this instance we had to use the Bind attribute designating “Motorcycle” as the prefix to the HTML elements we were interested in (i.e., the ones that made up the Motorcycle object).
This pattern is simple and elegant and appropriate in many situations. However, as views become more complicated, it also starts to break down since there is often an impedance mismatch between domain model objects and view model objects.

Pattern 3 – Dedicated view model that contains a custom view model entity
As views get more complicated it is often difficult to keep the domain model object in sync with concerns of the views.  In keeping with the example above, suppose we had requirements where we need to present the user a checkbox at the end of the screen if they want to add another motorcycle.  When the form is posted, the controller needs to make a determination based on this value to determine which view to show next. The last thing we want to do is to add this property to our domain model since this is strictly a presentation concern. Instead we can create a custom “view model entity” instead of passing the actual Motorcycle domain model object into the view. We’ll call it MotorcycleData:
   1:  public class MotorcycleData
   2:  {
   3:      public string Make { get; set; }
   4:      public string Model { get; set; }
   5:      public int Year { get; set; }
   6:      public string VIN { get; set; }
   7:      public bool AddAdditionalCycle { get; set; }
   8:  }
This pattern requires more work and it also requires a “mapping” translation layer to map back and forth between the Motorcycle and MotorcycleData objects but it is often well worth the effort as views get more complex.  This pattern is strongly advocated by the authors of MVC in Action (a book a highly recommend).  These ideas are further expanded in a post by Jimmy Bogard (one of the co-authors) in his post How we do MVC – View Models. I strongly recommended reading Bogard’s post (there are many interesting comments on that post as well). In it he discusses approaches to handling this pattern including using MVC Action filters and AutoMapper (I also recommend checking out AutoMapper).
Let’s continue to build out this pattern without the use of Action filters as an alternative. In real-world scenarios, these view models can get complex fast.  Not only do we need to map the data from Motorcycle to MotorcycleData, but we also might have numerous collections that need to be populated for dropdown lists, etc.  If we put all of this code in the controller, then the controller will quickly end up with a lot of code dedicated just to building the view model which is not desirable as we want to keep our controllers thin. Therefore, we can introduce a “builder” class that is concerned with building the view model.
   1:  public class MotorcycleViewModelBuilder
   2:  {
   3:      private IMotorcycleRepository motorcycleRepository;
   4:   
   5:      public MotorcycleViewModelBuilder(IMotorcycleRepository repository)
   6:      {
   7:          this.motorcycleRepository = repository;
   8:      }
   9:   
  10:      public MotorcycleViewModel Build()
  11:      {
  12:          // code here to fully build the view model 
  13:          // with methods in the repository
  14:      }
  15:  }
This allows our controller code to look something like this:
   1:  public ActionResult Edit(int id)
   2:  {
   3:      var viewModelBuilder = new MotorcycleViewModelBuilder(this.motorcycleRepository);
   4:      var motorcycleViewModel = viewModelBuilder.Build();
   5:      return this.View();
   6:  }
Our views can look pretty much the same as pattern #2 but now we have the comfort of knowing that we’re only passing in the data to the view that we need – no more, no less.  When the form is posted back, our controller’s Save() method can now look something like this:
   1:  public ActionResult Save([Bind(Prefix = "Motorcycle")]MotorcycleData motorcycleData)
   2:  {
   3:      var mapper = new MotorcycleMapper(motorcycleData);
   4:      Motorcycle motorcycle = mapper.Map();
   5:      this.motorcycleRepository.Save(motorcycle);
   6:      return this.RedirectToAction("Index");
   7:  }
Conceptually, this implementation is very similar to Bogard’s post but without the AutoMap attribute.  The AutoMap attribute allows us to keep some of this code out of the controller which can be quite nice.  One advantage to not using it is that the code inside the controller class is more obvious and explicit.  Additionally, our builder and mapper classes might need to build the objects from multiple sources and repositories. Internally in our mapper classes, you can still make great use of tools like AutoMapper.
In many complex real-world cases, some variation of pattern #3 is the best choice as it affords the most flexibility to the developer.

Considerations
How do you determine the best approach to take?  Here are some considerations to keep in mind:
Code Re-use – Certainly patterns #1 and #2 lend themselves best to code re-use as you are binding your views directly to your domain model objects. This leads to increased code brevity as mapping layers are not required. However, if your view concerns differ from your domain model (which they often will) options #1 and #2 begin to break down.
Impedance mismatch – Often there is an impedance mismatch between your domain model and the concerns of your view.  In these cases, option #3 gives the most flexibility.
Mapping Layer – If custom view entities are used as in option #3, you must ensure you establish a pattern for a mapping layer. Although this means more code that must be written, it gives the most flexibility and there are libraries available such as AutoMapper that make this easier to implement.
Validation – Although there are many ways to perform validation, one of the most common is to use libraries like Data Annotations. Although typical validations (e.g., required fields, etc.) will probably be the same between your domain models and your views, not all validation will always match.  Additionally, you may not always be in control of your domain models (e.g., in some enterprises the domain models are exposed via services that UI developers simply consume).  So there is a limit to how you can associate validations with those classes.  Yes, you can use a separate “meta data” class to designate validations but this duplicates some code similar to how a view model entity from option #3 would anyway. Therefore, option #3 gives you the absolute most control over UI validation.

Conclusion
The following has been a summary of several of the patterns that have emerged in dealing with view models. Although these have all been in the context of ASP.NET MVC, the problem with how best to deal with view models is also an issue with other frameworks like web forms as well. If you are able to bind directly to domain model in simple cases, that is the simplest and easiest solution. However, as your complexity grows, having distinct view models gives you the most overall flexibility.

References:
http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx

ASP.NET MVC : How to Use ViewModel with ASP.NET MVC ?

What is a Model ?
  • Parts of the application that implement the domain logic
  • also known as business logic
  • Domain logic handles the data that is passed between the database and the UI
  • For 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 :


ViewModel

Why We Use ViewModel ?

1. If you need to pass more than one thing to a strongly-typed view (which is best practice),
    you will generally want to create a separate class to do so.

2. This allows you to validate your ViewModel differently than your domain model for
    attribute-based validation scenarios

3. Can be used to help shape and format data.
    e.g: need a date or money value formatted a particular way?
          ViewModel is the best place to do it.

4. The use of a ViewModel can make the interaction between model and view more simple

             ViewModel Interaction with Model and View :

ViewModel Interaction with Model and View


Where Should We Create ViewModel (physically) ?

1. In a folder called ViewModels that resides in the root of the project. (small applications)

ViewModels that resides in the root of the project

2. As a .dll referenced from the MVC project (any size applications)

3. In a separate project(s) as a service layer, for large applications that generate
    view/content specific data. (enterprise applications)

Best Practices When Using ViewModels

1. Put only data that you'll render (use in View) in the ViewModel

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 ( How to Use ValueInjecter ? )


Let's Try with Simple Example

        - C#,MVC 3 and Visual Studio 2010 has been used.
        - Please follow an Inline Comments on Code. 
        - Simple application with product category drop down list, product name text box
          and Save button   

Our Domain Models Look Like Below

 public class Product
    {
        public Product() { Id = Guid.NewGuid(); Created = DateTime.Now; }
        public Guid Id { get; set; }
        public string ProductName { getset; }
        
        public virtual ProductCategory ProductCategory { getset; }
    }

 public class ProductCategory
    {
        public int Id { get; set; }
        public string CategoryName { get; set; }

        public virtual ICollection<Product> Products { get; set; }
    }

Our ViewModel Looks Like Below

 public class ProductViewModel
    {
        public Guid Id { get; set; }

        [Required(ErrorMessage = "required")]
        public string ProductName { get; set; }
        
        public int SelectedValue { get; set; }
    
        public virtual ProductCategory ProductCategory { get; set; }

        [DisplayName("Product Category")]
        public virtual ICollection<ProductCategory> ProductCategories { get; set; }
    }

Our Controller Action Methods Look Like Below

        [HttpGet]
        public ActionResult AddProduct() //generate view with categories for enter product data
        {
            //for get product categories from database
            var prodcutCategories = Repository.GetAllProductCategories();

            //for initialize viewmodel
            var productViewModel = new ProductViewModel();
            
            //assign values for viewmodel
            productViewModel.ProductCategories = prodcutCategories;

            //send viewmodel into UI (View)
            return View("AddProduct", productViewModel);
        }

        [HttpPost]
        public ActionResult AddProduct(ProductViewModel productViewModel) //save entered data
        {
            //get product category for selected drop down list value
            var prodcutCategory = Repository.GetProductCategory(productViewModel.SelectedValue);
            
            //for get all product categories
       var prodcutCategories = Repository.GetAllProductCategories();

            //for fill the drop down list when validation fails 
             productViewModel.ProductCategories = prodcutCategories;

            //for initialize Product domain model
            var productObj = new Product
                                     {
                                         ProductName = productViewModel.ProductName,
                                         ProductCategory = prodcutCategory,
                                     };

            if (ModelState.IsValid//check for any validation errors
            {
                //save recived data into database
                Repository.AddProduct(productObj);
                return RedirectToAction("AddProduct");
            }
            else
            {
                //when validation failed return viewmodel back to UI (View) 
                return View(productViewModel);
            }
        }

Our View Looks Like Below

Our View


AddProduct.cshtml

@model YourProject.ViewModels.ProductViewModel        //set your viewmodel here

 <div class="boxedForm">
  
@using (Html.BeginAbsoluteRouteForm("add", new { action = "AddProduct"},FormMethod.Post }))
         {
             <ul>
                     <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">
                  @Html.CompleteEditorFor(m => m.ProductName, labelOverride: "Product Name")
                  @Html.ValidationMessageFor(m => m.ProductName) 
                    </li>
            </ul>
                    <div class="action">
                        <button class="actionButton" type="submit">
                            <span>Save</span></button>
                    </div>
         }
   </div>

Repository Methods by using the Entity Framework

--- GetProductCategory() ---

//for get product category
public ProductCategory GetProductCategory(int categoryId)
{
return (from productCategory in Catalog.ProductCategories
where (productCategory.Id == categoryId)
select productCategory).FirstOrDefault();
}

---GetAllProductCategories()---

//for get all product categories
public List<ProductCategory> GetAllProductCategories()
{
return (from productCategory in Catalog.ProductCategories
select productCategory)
.OrderBy(p => p.CategoryName)
.ToList();
}



Conclusion
  • ViewModels help you organize and manage data in MVC applications when you need to work with more complex data than the other objects allow.
  • Using ViewModels gives you the flexibility to use data as you see fit.
  • ViewModels are generally a more flexible way to access multiple data sources than domain models.
  • Even for simple scenarios always try to use ViewModel approach to maintain consistency in Your coding practices
Reference:
http://sampathloku.blogspot.co.uk/2012/10/how-to-use-viewmodel-with-aspnet-mvc.html