As the OP asked, here is an example ViewModel template, or whatever I like to call it - ASP.NET MVC is executed correctly.
So why use a specific view model
- You should transmit information only to your opinion, which you need.
- Often you need to add additional view meta data (such as title / description attributes). They do not belong to your entities.
- Using TryUpdateModel / UpdateModel is incorrect. Do not use (I will explain why).
- It is very rare that your view models will exactly match your objects. People often end up adding an extra jerk to their entities or (not much better) just using the ViewBag and not the strongly typed properties of the view model.
- If you use ORM, you may encounter problems with Lazy loaded properties (N + 1). Your opinions should not cause inquiries.
We will start with a simple object:
public class Product { public int Id {get;set;} public string Name {get;set;} public string Description {get;set;} public decimal Price {get;set;} }
And let's say you have a simple form in which the user can only update the Product Name and Description . But you are using (very greedy) TryUpdateModel.
So I use any number of tools (like Fiddler) to create a POST and send the following:
Name = WhatverIWant & Description = UnluckyFool & Price = 0
Itโs good that the ASP.NET MVC modelโs middleware will check the collection of input forms, it can be seen that these properties exist on your entity and automatically bind them for you. Therefore, when you call "TryUpdateModel" on an entity that you just retrieved from your database, all relevant properties will be updated (including the price!). Time for a new option.
View specific model
public class EditProductViewModel { [HiddenInput] public Guid Id {get;set;} [Required] [DisplayName("Product Name")] public string Name {get;set;} [AllowHtml] [DataType(DataType.MultilineText)] public string Description {get;set;} }
This contains only the properties that we need in our view. Please note that we also added some validation attributes, display attributes, and some specific mvc attributes.
Not limited to what we have in our model, we can make your views cleaner. For example, we could display the entire editing form, having in our opinion the following:
@Html.EditorFor(model => model)
Mvc will check all the attributes that we have added to our view model and automatically include checks, labels, and the correct input fields (i.e. a text field for the description).
Form input
[HttpPost] public ActionResult EditProduct(EditProductViewModel model) { var product = repository.GetById(model.Id); if (product == null) { return HttpNotFound(); }
From this code, it is pretty obvious what it does. We do not have any undesirable effects when we update our object, since we explicitly set properties for our entity.
Hope this explains the View-Model enough for you to use it.