What is ViewModel in MVC?










372














I am new to ASP.NET MVC. I have a problem in understanding the purpose of a ViewModel.



What is a ViewModel and why do we need a ViewModel for an ASP.NET MVC Application?



It is better if I can have a simple example.










share|improve this question



















  • 4




    This post is what you look for - "What is an ASP.NET MVC ViewModel?"
    – EL Yusubov
    Jun 17 '12 at 19:43







  • 6




    This article looks great: rachelappel.com/…
    – Andrew
    Sep 19 '14 at 19:03










  • possible duplicate of In MVC, what is a ViewModel?
    – rogerdeuce
    Jul 10 '15 at 18:24















372














I am new to ASP.NET MVC. I have a problem in understanding the purpose of a ViewModel.



What is a ViewModel and why do we need a ViewModel for an ASP.NET MVC Application?



It is better if I can have a simple example.










share|improve this question



















  • 4




    This post is what you look for - "What is an ASP.NET MVC ViewModel?"
    – EL Yusubov
    Jun 17 '12 at 19:43







  • 6




    This article looks great: rachelappel.com/…
    – Andrew
    Sep 19 '14 at 19:03










  • possible duplicate of In MVC, what is a ViewModel?
    – rogerdeuce
    Jul 10 '15 at 18:24













372












372








372


194





I am new to ASP.NET MVC. I have a problem in understanding the purpose of a ViewModel.



What is a ViewModel and why do we need a ViewModel for an ASP.NET MVC Application?



It is better if I can have a simple example.










share|improve this question















I am new to ASP.NET MVC. I have a problem in understanding the purpose of a ViewModel.



What is a ViewModel and why do we need a ViewModel for an ASP.NET MVC Application?



It is better if I can have a simple example.







asp.net-mvc viewmodel






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 24 '18 at 13:19









MikaS

6,929142034




6,929142034










asked Jun 16 '12 at 14:36









unique

2,12241824




2,12241824







  • 4




    This post is what you look for - "What is an ASP.NET MVC ViewModel?"
    – EL Yusubov
    Jun 17 '12 at 19:43







  • 6




    This article looks great: rachelappel.com/…
    – Andrew
    Sep 19 '14 at 19:03










  • possible duplicate of In MVC, what is a ViewModel?
    – rogerdeuce
    Jul 10 '15 at 18:24












  • 4




    This post is what you look for - "What is an ASP.NET MVC ViewModel?"
    – EL Yusubov
    Jun 17 '12 at 19:43







  • 6




    This article looks great: rachelappel.com/…
    – Andrew
    Sep 19 '14 at 19:03










  • possible duplicate of In MVC, what is a ViewModel?
    – rogerdeuce
    Jul 10 '15 at 18:24







4




4




This post is what you look for - "What is an ASP.NET MVC ViewModel?"
– EL Yusubov
Jun 17 '12 at 19:43





This post is what you look for - "What is an ASP.NET MVC ViewModel?"
– EL Yusubov
Jun 17 '12 at 19:43





6




6




This article looks great: rachelappel.com/…
– Andrew
Sep 19 '14 at 19:03




This article looks great: rachelappel.com/…
– Andrew
Sep 19 '14 at 19:03












possible duplicate of In MVC, what is a ViewModel?
– rogerdeuce
Jul 10 '15 at 18:24




possible duplicate of In MVC, what is a ViewModel?
– rogerdeuce
Jul 10 '15 at 18:24












11 Answers
11






active

oldest

votes


















538














A view model represents the data that you want to display on your view/page, whether it be used for static text or for input values (like textboxes and dropdown lists) that can be added to the database (or edited). It is something different than your domain model. It is a model for the view.



Let us say that you have an Employee class that represents your employee domain model and it contains the following properties (unique identifier, first name, last name and date created):



public class Employee : IEntity

public int Id get; set;

public string FirstName get; set;

public string LastName get; set;

public DateTime DateCreated get; set;



View models differ from domain models in that view models only contain the data (represented by properties) that you want to use on your view. For example, lets say that you want to add a new employee record, your view model might look like this:



public class CreateEmployeeViewModel

public string FirstName get; set;

public string LastName get; set;



As you can see it only contains two of the properties. These two properties are also in the employee domain model. Why is this you may ask? Id might not be set from the view, it might be auto generated by the Employee table. And DateCreated might also be set in the stored procedure or in the service layer of your application. So Id and DateCreated are not needed in the view model. You might want to display these two properties when you view an employee’s details (an employee that has already been captured) as static text.



When loading the view/page, the create action method in your employee controller will create an instance of this view model, populate any fields if required, and then pass this view model to the view/page:



public class EmployeeController : Controller

private readonly IEmployeeService employeeService;

public EmployeeController(IEmployeeService employeeService)

this.employeeService = employeeService;


public ActionResult Create()

CreateEmployeeViewModel model = new CreateEmployeeViewModel();

return View(model);


public ActionResult Create(CreateEmployeeViewModel model)

// Do what ever needs to be done before adding the employee to the database




Your view/page might look like this (assuming you are using ASP.NET MVC and the Razor view engine):



@model MyProject.Web.ViewModels.CreateEmployeeViewModel

<table>
<tr>
<td><b>First Name:</b></td>
<td>@Html.TextBoxFor(m => m.FirstName, new maxlength = "50", size = "50" )
@Html.ValidationMessageFor(m => m.FirstName)
</td>
</tr>
<tr>
<td><b>Last Name:</b></td>
<td>@Html.TextBoxFor(m => m.LastName, new maxlength = "50", size = "50" )
@Html.ValidationMessageFor(m => m.LastName)
</td>
</tr>
</table>


Validation would thus be done only on FirstName and LastName. Using Fluent Validation you might have validation like this:



public class CreateEmployeeViewModelValidator : AbstractValidator<CreateEmployeeViewModel>

public CreateEmployeeViewModelValidator()

RuleFor(m => m.FirstName)
.NotEmpty()
.WithMessage("First name required")
.Length(1, 50)
.WithMessage("First name must not be greater than 50 characters");

RuleFor(m => m.LastName)
.NotEmpty()
.WithMessage("Last name required")
.Length(1, 50)
.WithMessage("Last name must not be greater than 50 characters");




And with Data Annotations it might look this:



public class CreateEmployeeViewModel : ViewModelBase

[Display(Name = "First Name")]
[Required(ErrorMessage = "First name required")]
public string FirstName get; set;

[Display(Name = "Last Name")]
[Required(ErrorMessage = "Last name required")]
public string LastName get; set;



The key thing to remember is that the view model only represents the data that you want to use, nothing else. You can imagine all the unnecessary code and validation if you have a domain model with 30 properties and you only want to update a single value. Given this scenario you would only have this one value/property in the view model and not all the properties that are in the domain object.



A view model might not only have data from one database table. It can combine data from another table. Take my example above about adding a new employee record. Besides adding just the first and last names you might also want to add the department of the employee. This list of departments will come from your Departments table. So now you have data from the Employees and Departments tables in one view model. You will just then need to add the following two properties to your view model and populate it with data:



public int DepartmentId get; set; 

public IEnumerable<Department> Departments get; set;


When editing employee data (an employee that has already been added to the database) it wouldn’t differ much from my example above. Create a view model, call it for example EditEmployeeViewModel. Only have the data that you want to edit in this view model, like first name and last name. Edit the data and click the submit button. I wouldn’t worry too much about the Id field because the Id value will probably been in the URL, for example:



http://www.yourwebsite.com/Employee/Edit/3


Take this Id and pass it through to your repository layer, together with your first name and last name values.



When deleting a record, I normally follow the same path as with the edit view model. I would also have a URL, for example:



http://www.yourwebsite.com/Employee/Delete/3


When the view loads up for the first time I would get the employee’s data from the database using the Id of 3. I would then just display static text on my view/page so that the user can see what employee is being deleted. When the user clicks the Delete button, I would just use the Id value of 3 and pass it to my repository layer. You only need the Id to delete a record from the table.



Another point, you don’t really need a view model for every action. If it is simple data then it would be fine to only use EmployeeViewModel. If it is complex views/pages and they differ from each other then I would suggest you use separate view models for each.



I hope this clears up any confusion that you had about view models and domain models.






share|improve this answer


















  • 5




    @Kenny: Then show it :) What I was trying to say is lets say you have a domain model with 50 properties and your view only needs to display 5 then it is no use in sending all 50 properties just to display 5.
    – Brendan Vogt
    Jul 17 '13 at 5:44






  • 4




    @BrendanVogt – you did a good job explaining that, but I don't understand what the cost is of "sending all 50 properties". Other code has already created a Model object, with all 50 properties, and it doesn't seem worthwhile to maintain another class just to not send 45 properties – especially if you might want to send any one of those 45 properties in the future.
    – Kenny Evitt
    Jul 17 '13 at 13:01






  • 5




    @BrendanVogt – I think maybe LukLed's answer helps me understand why these might be useful, particularly that a ViewModel (can) "... combine values from different database entities" [where I'm assuming that the phrase is just as true were "database entities" to be replaced with "Model objects"]. But still, what specific problems were ViewModels intended to address? Do you have any links? I couldn't find anything myself. [And I apologize if I seem to be picking on you!]
    – Kenny Evitt
    Jul 17 '13 at 13:09






  • 6




    +1 for mentioning fluent validation
    – MUG4N
    Oct 12 '13 at 17:37






  • 3




    I'm sorry for being critical but this answer is, unfortunately, incomplete. Defining a viewmodel as only what you need display on your page is like asking "What is a car?" and receiving an answer "Its not an airplane". Well thats true but not very helpful. The more correct definition of a VM is "Everything you need to render your page." If you read down to the bottom I have identified the components you need to build your VM's correctly and easily, in many cases leveraging your existing domain models and presentation models.
    – Sam
    May 15 '15 at 16:43


















125














View model is a class that represents the data model used in a specific view. We could use this class as a model for a login page:



public class LoginPageVM

[Required(ErrorMessage = "Are you really trying to login without entering username?")]
[DisplayName("Username/e-mail")]
public string UserName get; set;
[Required(ErrorMessage = "Please enter password:)")]
[DisplayName("Password")]
public string Password get; set;
[DisplayName("Stay logged in when browser is closed")]
public bool RememberMe get; set;



Using this view model you can define the view (Razor view engine):



@model CamelTrap.Models.ViewModels.LoginPageVM

@using (Html.BeginForm())
@Html.EditorFor(m => m);
<input type="submit" value="Save" class="submit" />



And actions:



[HttpGet]
public ActionResult LoginPage()

return View();


[HttpPost]
public ActionResult LoginPage(LoginPageVM model)

...code to login user to application...
return View(model);



Which produces this result (screen is taken after submitting form, with validation messages):





As you can see, a view model has many roles:



  • View models documents a view by consisting only fields, that are represented in view.

  • View models may contain specific validation rules using data annotations or IDataErrorInfo.

  • View model defines how a view should look (for LabelFor,EditorFor,DisplayFor helpers).

  • View models can combine values from different database entities.

  • You can specify easily display templates for view models and reuse them in many places using DisplayFor or EditorFor helpers.

Another example of a view model and its retrieval: We want to display basic user data, his privileges and users name. We create a special view model, which contains only the required fields. We retrieve data from different entities from database, but the view is only aware of the view model class:



public class UserVM 
public int ID get; set;
public string FirstName get; set;
public string LastName get; set;
public bool IsAdministrator get; set;
public string MothersName get; set;



Retrieval:



var user = db.userRepository.GetUser(id);

var model = new UserVM()
ID = user.ID,
FirstName = user.FirstName,
LastName = user.LastName,
IsAdministrator = user.Proviledges.IsAdministrator,
MothersName = user.Mother.FirstName + " " + user.Mother.LastName






share|improve this answer


















  • 4




    thank you,This is very helpful
    – unique
    Jun 16 '12 at 16:30











  • I thin user.Mother.FirstName + " " + user.Mother.LastName should be done in View Model End. All Logic should be done on View Model end.
    – Kurkula
    Jun 21 '15 at 16:38






  • 3




    @Chandana: I believe simple concatenation can be done in view model. There is no reason to expose two fields, if they are meant to be presented together.
    – LukLed
    Jun 22 '15 at 12:45


















68














Edit: I updated this answer on my Blog:



http://www.samwheat.com/Post/The-function-of-ViewModels-in-MVC-web-development



My answer is a bit lengthy but I think it is important to compare view models to other types of commonly used models to understand why they are different and why they are necessary.



To summarize, and to directly answer the question that is asked:



Generally speaking, a view model is an object that contains all the properties and methods necessary to render a view. View model properties are often related to data objects such as customers and orders and in addition they also contain properties related to the page or application itself such as user name, application name etc. View models provide a convenient object to pass to a rendering engine to create a html page. One of many reasons to use a view model is that view models provide a way to unit test certain presentation tasks such as handling user input, validating data, retrieving data for display, etc.



Here is a comparison of Entity models (a.ka. DTO's a.ka. models), Presentation Models, and View Models.



Data Transfer Objects a.k.a “Model”



A Data Transfer Object (DTO) is a class with properties that match a table schema in a database. DTO’s are named for their common usage for shuttling data to and from a data store.

Characteristics of DTO’s:



• Are business objects – their definition is dependent on application data.



• Usually contain properties only – no code.



• Primarily used for transporting data to and from a database.



• Properties exactly or closely match fields on a specific table in a data store.



Database tables are usually normalized therefore DTO’s are usually normalized also. This makes them of limited use for presenting data. However, for certain simple data structures they often do quite well.



Here are two examples of what DTO’s might look like:



public class Customer

public int ID get; set;
public string CustomerName get; set;



public class Order

public int ID get; set;
public int CustomerID get; set;
public DateTime OrderDate get; set;
public Decimal OrderAmount get; set;





Presentation Models



A presentation model is a utility class that is used to render data on a screen or report. Presentation models are typically used to model complex data structures that are composed from data from multiple DTO’s. Presentation models often represent a denormalized view of data.



Characteristics of Presentation Models:



• Are business objects – their definition is dependent on application data.



• Contain mostly properties. Code is typically limited to formatting data or converting to or from a DTO. Presentation Models should not contain business logic.



• Often present a denormalized view of data. That is, they often combine properties from multiple DTO’s.



• Often contain properties of a different base type than a DTO. For example dollar amounts may be represented as strings so they can contain commas and a currency symbol.



• Often defined by how they are used as well as their object characteristics. In other words, a simple DTO that is used as the backing model for rendering a grid is in fact also a presentation model in the context of that grid.



Presentation models are used “as needed” and “where needed” (whereas DTO’s are usually tied to the database schema). A presentation model may be used to model data for an entire page, a grid on a page, or a dropdown on a grid on a page. Presentation models often contain properties that are other presentation models. Presentation models are often constructed for a single-use purpose such as to render a specific grid on a single page.



An example presentation model:



public class PresentationOrder

public int OrderID get; set;
public DateTime OrderDate get; set;
public string PrettyDate get return OrderDate.ToShortDateString();
public string CustomerName get; set;
public Decimal OrderAmount get; set;
public string PrettyAmount get return string.Format("0:C", OrderAmount);



View Models



A view model is similar to a presentation model in that is a backing class for rendering a view. However it is very different from a Presentation Model or a DTO in how it is constructed. View models often contain the same properties as presentation models and DTO’s and for this reason they are often confused one for the other.



Characteristics of View Models:



• Are the single source of data used to render a page or screen. Usually this means that a view model will expose every property that any control on the page will need to render itself correctly. Making the view model the single source of data for the view greatly improves its capability and value for unit testing.



• Are composite objects that contain properties that consist of application data as well as properties that are used by application code. This characteristic is crucial when designing the view model for reusability and is discussed in the examples below.



• Contain application code. View Models usually contain methods that are called during rendering and when the user is interacting with the page. This code typically relates to event handling, animation, visibility of controls, styling, etc.



• Contain code that calls business services for the purpose of retrieving data or sending it to a database server. This code is often mistakenly placed in a controller. Calling business services from a controller usually limits the usefulness of the view model for unit testing. To be clear, view models themselves should not contain business logic but should make calls to services which do contain business logic.



• Often contain properties which are other view models for other pages or screens.



• Are written “per page” or “per screen”. A unique View Model is typically written for every page or screen in an application.



• Usually derive from a base class since most pages and screens share common properties.



View Model Composition



As stated earlier, view models are composite objects in that they combine application properties and business data properties on a single object. Examples of commonly used application properties that are used on view models are:



• Properties that are used to display application state such as error messages, user name, status, etc.



• Properties used to format, display, stylize, or animate controls.



• Properties used for data binding such as list objects and properties that hold intermediate data that is input by the user.



The following examples show why the composite nature of view models is important and how we can best construct a View Model that efficient and reusable.



Assume we are writing a web application. One of the requirements of the application design is that the page title, user name, and application name must be displayed on every page. If we want to create a page to display a presentation order object, we may modify the presentation model as follows:



public class PresentationOrder

public string PageTitle get; set;
public string UserName get; set;
public string ApplicationName get; set;
public int OrderID get; set;
public DateTime OrderDate get; set;
public string PrettyDate get return OrderDate.ToShortDateString();
public string CustomerName get; set;
public Decimal OrderAmount get; set;
public string PrettyAmount get return string.Format("0:C", OrderAmount);



This design might work… but what if we want to create a page that will display a list of orders? The PageTitle, UserName, and ApplicationName properties will be repeated and become unwieldy to work with. Also, what if we want to define some page-level logic in the constructor of the class? We can no longer do that if we create an instance for every order that will be displayed.



Composition over inheritance



Here is a way we might re-factor the order presentation model such that it become a true view model and will be useful for displaying a single PresentationOrder object or a collection of PresentationOrder objects:



public class PresentationOrderVM

// Application properties
public string PageTitle get; set;
public string UserName get; set;
public string ApplicationName get; set;

// Business properties
public PresentationOrder Order get; set;



public class PresentationOrderVM

// Application properties
public string PageTitle get; set;
public string UserName get; set;
public string ApplicationName get; set;

// Business properties
public List<PresentationOrder> Orders get; set;



Looking at the above two classes we can see that one way to think about a view model is that it is a presentation model that contains another presentation model as a property. The top level presentation model (i.e. view model) contains properties that are relevant to the page or application while presentation model (property) contains properties that are relevant to application data.



We can take our design a step further and create a base view model class that can be used not only for PresentationOrders, but for any other class as well:



public class BaseViewModel

// Application properties
public string PageTitle get; set;
public string UserName get; set;
public string ApplicationName get; set;



Now we can simplify our PresentationOrderVM like this:



public class PresentationOrderVM : BaseViewModel

// Business properties
public PresentationOrder Order get; set;


public class PresentationOrderVM : BaseViewModel

// Business properties
public List<PresentationOrder> Orders get; set;



We can make our BaseViewModel even more re-usable by making it generic:



public class BaseViewModel<T>

// Application properties
public string PageTitle get; set;
public string UserName get; set;
public string ApplicationName get; set;

// Business property
public T BusinessObject get; set;



Now our implementations are effortless:



public class PresentationOrderVM : BaseViewModel<PresentationOrder>

// done!


public class PresentationOrderVM : BaseViewModel<List<PresentationOrder>>

// done!






share|improve this answer


















  • 1




    Sam Thank You!! this helped me fully grasp the multi-faceted entity that is a: View-Model. I'm a college student just learning the MVC architecture, and this clarified a bunch of the capable functionalities that are exposed to the developer. If I could I would put a star next to your answer.
    – Chef_Code
    Jan 26 '16 at 3:13







  • 1




    @Sam 'View models often contain the same properties as presentation models and DTO’s and for this reason they are often confused one for the other.' Does that mean they're commonly used instead of presentation models, or are they meant to contain the presentation models/dtos?
    – Alexander Derck
    Feb 1 '17 at 8:24






  • 2




    @AlexanderDerck They are used for different purposes. They are confused one for the other (in error). No, you typically will not use a pres model in place of a view model. Much more common is that the VM "contains" the presentation model i.e. MyViewModel<MyPresModel>
    – Sam
    Feb 1 '17 at 15:05






  • 1




    Way cool Sam! Thanks
    – Stokely
    Jul 13 '17 at 23:48






  • 1




    @Sam Assuming model objects are live objects e.g. nhibernate models.. so by having BusinessObject aren't we exposing model/live objects directly to the view? i.e. the business object can be used to modify the database state directly? Also, what about nested view models? That would require multiple business object properties, right?
    – Muhammad Ali
    Sep 30 '17 at 9:54



















22














If you have properties specific to the view, and not related to the DB/Service/Data store, it is a good practice to use ViewModels. Say, you want to leave a checkbox selected based on a DB field (or two) but the DB field itself isn't a boolean. While it is possible to create these properties in the Model itself and keep it hidden from the binding to data, you may not want to clutter the Model depending on the amount of such fields and transactions.



If there are too few view-specific data and/or transformations, you can use the Model itself






share|improve this answer




























    14














    I didn't read all the posts but every answer seems to be missing one concept that really helped me "get it"...



    If a Model is akin to a database Table, then a ViewModel is akin to a database View - A view typically either returns small amounts of data from one table, or, complex sets of data from multiple tables (joins).



    I find myself using ViewModels to pass info into a view/form, and then transfering that data into a valid Model when the form posts back to the controller - also very handy for storing Lists(IEnumerable).






    share|improve this answer




























      10














      MVC doesn't have a viewmodel: it has a model, view and controller. A viewmodel is part of MVVM (Model-View-Viewmodel). MVVM is derived from the Presentation Model and is popularized in WPF. There should also be a model in MVVM, but most people miss the point of that pattern completely and they will only have a view and a viewmodel. The model in MVC is similar to the model in MVVM.



      In MVC the process is split into 3 different responsibilities:



      • View is responsible for presenting the data to the user

      • A controller is responsible for the page flow

      • A model is responsible for the business logic

      MVC is not very suitable for web applications. It is a pattern introduced by Smalltalk for creating desktop applications. A web environment behaves completely different. It doesn't make much sense to copy a 40-year old concept from the desktop development and paste it into a web enviroment. However a lot of people think this is ok, because their application compiles and returns the correct values. That is, in my opinion, not enough to declare a certain design choice as ok.



      An example of a model in a web application could be:



      public class LoginModel

      private readonly AuthenticationService authentication;

      public LoginModel(AuthenticationService authentication)

      this.authentication = authentication;


      public bool Login()

      return authentication.Login(Username, Password);


      public string Username get; set;
      public string Password get; set;



      The controller can use it like this:



      public class LoginController

      [HttpPost]
      public ActionResult Login(LoginModel model)

      bool success = model.Login();

      if (success)

      return new RedirectResult("/dashboard");

      else

      TempData["message"] = "Invalid username and/or password";
      return new RedirectResult("/login");





      Your controller methods and your models will be small, easily testable and to the point.






      share|improve this answer






















      • Thank you for the insight into MVVM architecture, but why is MVC not OK? Your reasoning is questionable and suspect to favoritism. Granted I know nothing about MVVM, but if an architecture such as MVC can mimic the behavior with-out having to write 50k lines of code, then whats the big deal?
        – Chef_Code
        Jan 26 '16 at 3:23











      • @Chef_Code: It is not questionable or favoritism: just read the original paper about MVC. Going back to the source is much better than blindly following the herd without question (aka "best practices"). MVC is meant for much smaller units: e.g. a button on a screen is composed of a model, view and controller. In Web-MVC the entire page has a controller, a model and a view. The model and view are supposed to be connected, so that changes in the model are immediately reflected in the view and vice versa. Mimicking is a very big deal. An architecture shouldn't lie to it's developers.
        – Jeroen
        Jan 26 '16 at 11:49






      • 1




        @jeroen The acronym MVC has been stolen and mangled. Yes MVC does not have a VM but it also doesn't have a Repository or a service layer and those objects are widely used in web sites. I believe the OP is asking "how do I introduce and use a VM in MVC". In the new meaning of MVC a model is not where business logic belongs. Business logic belongs in a service layer for a web or a desktop app using MVC or MVVM. The term model describes the business objects that are passed to/from the service layer. These definitions are vastly different from the original description of MVC.
        – Sam
        Feb 15 '16 at 16:46







      • 1




        @Sam Not everything that is part of a website, can be called part of MVC. There is no new meaning of MVC. There is the correct meaning and the "something completely unrelated that people confuse with MVC"-meaning. Saying that the model is responsible for the business logic, is not the same as business logic is coded in the model. Most of the time the model acts as a facade to the application.
        – Jeroen
        Feb 23 '16 at 13:48










      • The main flaw I see in Microsoft's MVC is the locking of a Model with a View. That itself defeats the whole purpose of all this separation that's been going on in N-Tier designs the past 20 years. They wasted our time forcing us to use "WebForms" in 2002 which was another Desktop-inspired model hoisted onto the Web World. Now they've tossded that out but hoisted yet again another desktop model on this new paradigm for web dev. In the mean time Google and others are building giant client-side models that separate it all. Im thinking old ASP VBScript from 1998 was their truest web dev system.
        – Stokely
        Jul 13 '17 at 23:58



















      10














      A lot of big examples, let me explain in clear and crispy way.



      ViewModel = Model that is created to serve the view.



      ASP.NET MVC view can't have more than one model so if we need to display properties from more than one models into the view, it is not possible. ViewModel serves this purpose.



      View Model is a model class that can hold only those properties that is required for a view. It can also contains properties from more than one entities (tables) of the database. As the name suggests, this model is created specific to the View requirements.



      Few examples of View Models are below



      • To list data from more than entities in a view page – we can create a
        View model and have properties of all the entities for which we want
        to list data. Join those database entities and set View model
        properties and return to the View to show data of different
        entities in one tabular form

      • View model may define only specific fields of a single entity that is
        required for the View.

      ViewModel can also be used to insert, update records into more than one entities however the main use of ViewModel is to display columns from multiple entities (model) into a single view.



      The way of creating ViewModel is same as creating Model, the way of creating view for the Viewmodel is same as creating view for Model.



      Here is a small example of List data using ViewModel.



      Hope this will be useful.






      share|improve this answer




























        10














        View model a is simple class which can contain more than one class property. We use it to inherit all the required properties, e.g. I have two classes Student and Subject



        Public class Student

        public int Id get; set;
        public string Name get; set;

        Public class Subject

        public int SubjectID get; set;
        public string SubjectName get; set;



        Now we want to display records student's Name and Subject's Name in View (In MVC), but it's not possible to add more than one classes like:



         @model ProjectName.Model.Student 
        @model ProjectName.Model.Subject


        the code above will throw an error...



        Now we create one class and can give it any name, but this format "XyzViewModel" will make it easier to understand. It is inheritance concept.
        Now we create a third class with the following name:



        public class StudentViewModel:Subject

        public int ID get; set;
        public string Name get; set;



        Now we use this ViewModel in View




        @model ProjectName.Model.StudentViewModel




        Now we are able to access all the properties of StudentViewModel and inherited class in View.






        share|improve this answer






























          4














          ViewModel is workarround that patches the conceptual clumsiness of the MVC framework. It represents the 4th layer in the 3-layer Model-View-Controller architecture. when Model (domain model) is not appropriate, too big (bigger than 2-3 fields) for the View, we create smaller ViewModel to pass it to the View.






          share|improve this answer




























            1














            A view model is a conceptual model of data. Its use is to for example either get a subset or combine data from different tables.



            You might only want specific properties, so this allows you to only load those and not additional unneccesary properties






            share|improve this answer




























              1














              • ViewModel contain fields that are represented in the view (for
                LabelFor,EditorFor,DisplayFor helpers)

              • ViewModel can have specific validation rules using data annotations
                or IDataErrorInfo.

              • ViewModel can have multiple entities or objects from different data
                models or data source.

              Designing ViewModel



              public class UserLoginViewModel 

              [Required(ErrorMessage = "Please enter your username")]
              [Display(Name = "User Name")]
              [MaxLength(50)]
              public string UserName get; set;
              [Required(ErrorMessage = "Please enter your password")]
              [Display(Name = "Password")]
              [MaxLength(50)]
              public string Password get; set;



              Presenting the viewmodel in the view



              @model MyModels.UserLoginViewModel 
              @
              ViewBag.Title = "User Login";
              Layout = "~/Views/Shared/_Layout.cshtml";

              @using (Html.BeginForm())

              <div class="editor-label">
              @Html.LabelFor(m => m.UserName)
              </div>
              <div class="editor-field">
              @Html.TextBoxFor(m => m.UserName)
              @Html.ValidationMessageFor(m => m.UserName)
              </div>
              <div class="editor-label">
              @Html.LabelFor(m => m.Password)
              </div>
              <div class="editor-field">
              @Html.PasswordFor(m => m.Password)
              @Html.ValidationMessageFor(m => m.Password)
              </div>
              <p>
              <input type="submit" value="Log In" />
              </p>
              </div>



              Working with Action



              public ActionResult Login()

              return View();

              [HttpPost]
              public ActionResult Login(UserLoginViewModel user)

              // To acces data using LINQ
              DataClassesDataContext mobjentity = new DataClassesDataContext();
              if (ModelState.IsValid)

              try

              var q = mobjentity.tblUsers.Where(m => m.UserName == user.UserName && m.Password == user.Password).ToList();
              if (q.Count > 0)

              return RedirectToAction("MyAccount");

              else

              ModelState.AddModelError("", "The user name or password provided is incorrect.");


              catch (Exception ex)



              return View(user);



              1. In ViewModel put only those fields/data that you want to display on
                the view/page.

              2. Since view reperesents the properties of the ViewModel, hence it is
                easy for rendering and maintenance.

              3. Use a mapper when ViewModel become more complex.





              share|improve this answer



















                protected by Samuel Liew Oct 5 '15 at 9:21



                Thank you for your interest in this question.
                Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                Would you like to answer one of these unanswered questions instead?














                11 Answers
                11






                active

                oldest

                votes








                11 Answers
                11






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                538














                A view model represents the data that you want to display on your view/page, whether it be used for static text or for input values (like textboxes and dropdown lists) that can be added to the database (or edited). It is something different than your domain model. It is a model for the view.



                Let us say that you have an Employee class that represents your employee domain model and it contains the following properties (unique identifier, first name, last name and date created):



                public class Employee : IEntity

                public int Id get; set;

                public string FirstName get; set;

                public string LastName get; set;

                public DateTime DateCreated get; set;



                View models differ from domain models in that view models only contain the data (represented by properties) that you want to use on your view. For example, lets say that you want to add a new employee record, your view model might look like this:



                public class CreateEmployeeViewModel

                public string FirstName get; set;

                public string LastName get; set;



                As you can see it only contains two of the properties. These two properties are also in the employee domain model. Why is this you may ask? Id might not be set from the view, it might be auto generated by the Employee table. And DateCreated might also be set in the stored procedure or in the service layer of your application. So Id and DateCreated are not needed in the view model. You might want to display these two properties when you view an employee’s details (an employee that has already been captured) as static text.



                When loading the view/page, the create action method in your employee controller will create an instance of this view model, populate any fields if required, and then pass this view model to the view/page:



                public class EmployeeController : Controller

                private readonly IEmployeeService employeeService;

                public EmployeeController(IEmployeeService employeeService)

                this.employeeService = employeeService;


                public ActionResult Create()

                CreateEmployeeViewModel model = new CreateEmployeeViewModel();

                return View(model);


                public ActionResult Create(CreateEmployeeViewModel model)

                // Do what ever needs to be done before adding the employee to the database




                Your view/page might look like this (assuming you are using ASP.NET MVC and the Razor view engine):



                @model MyProject.Web.ViewModels.CreateEmployeeViewModel

                <table>
                <tr>
                <td><b>First Name:</b></td>
                <td>@Html.TextBoxFor(m => m.FirstName, new maxlength = "50", size = "50" )
                @Html.ValidationMessageFor(m => m.FirstName)
                </td>
                </tr>
                <tr>
                <td><b>Last Name:</b></td>
                <td>@Html.TextBoxFor(m => m.LastName, new maxlength = "50", size = "50" )
                @Html.ValidationMessageFor(m => m.LastName)
                </td>
                </tr>
                </table>


                Validation would thus be done only on FirstName and LastName. Using Fluent Validation you might have validation like this:



                public class CreateEmployeeViewModelValidator : AbstractValidator<CreateEmployeeViewModel>

                public CreateEmployeeViewModelValidator()

                RuleFor(m => m.FirstName)
                .NotEmpty()
                .WithMessage("First name required")
                .Length(1, 50)
                .WithMessage("First name must not be greater than 50 characters");

                RuleFor(m => m.LastName)
                .NotEmpty()
                .WithMessage("Last name required")
                .Length(1, 50)
                .WithMessage("Last name must not be greater than 50 characters");




                And with Data Annotations it might look this:



                public class CreateEmployeeViewModel : ViewModelBase

                [Display(Name = "First Name")]
                [Required(ErrorMessage = "First name required")]
                public string FirstName get; set;

                [Display(Name = "Last Name")]
                [Required(ErrorMessage = "Last name required")]
                public string LastName get; set;



                The key thing to remember is that the view model only represents the data that you want to use, nothing else. You can imagine all the unnecessary code and validation if you have a domain model with 30 properties and you only want to update a single value. Given this scenario you would only have this one value/property in the view model and not all the properties that are in the domain object.



                A view model might not only have data from one database table. It can combine data from another table. Take my example above about adding a new employee record. Besides adding just the first and last names you might also want to add the department of the employee. This list of departments will come from your Departments table. So now you have data from the Employees and Departments tables in one view model. You will just then need to add the following two properties to your view model and populate it with data:



                public int DepartmentId get; set; 

                public IEnumerable<Department> Departments get; set;


                When editing employee data (an employee that has already been added to the database) it wouldn’t differ much from my example above. Create a view model, call it for example EditEmployeeViewModel. Only have the data that you want to edit in this view model, like first name and last name. Edit the data and click the submit button. I wouldn’t worry too much about the Id field because the Id value will probably been in the URL, for example:



                http://www.yourwebsite.com/Employee/Edit/3


                Take this Id and pass it through to your repository layer, together with your first name and last name values.



                When deleting a record, I normally follow the same path as with the edit view model. I would also have a URL, for example:



                http://www.yourwebsite.com/Employee/Delete/3


                When the view loads up for the first time I would get the employee’s data from the database using the Id of 3. I would then just display static text on my view/page so that the user can see what employee is being deleted. When the user clicks the Delete button, I would just use the Id value of 3 and pass it to my repository layer. You only need the Id to delete a record from the table.



                Another point, you don’t really need a view model for every action. If it is simple data then it would be fine to only use EmployeeViewModel. If it is complex views/pages and they differ from each other then I would suggest you use separate view models for each.



                I hope this clears up any confusion that you had about view models and domain models.






                share|improve this answer


















                • 5




                  @Kenny: Then show it :) What I was trying to say is lets say you have a domain model with 50 properties and your view only needs to display 5 then it is no use in sending all 50 properties just to display 5.
                  – Brendan Vogt
                  Jul 17 '13 at 5:44






                • 4




                  @BrendanVogt – you did a good job explaining that, but I don't understand what the cost is of "sending all 50 properties". Other code has already created a Model object, with all 50 properties, and it doesn't seem worthwhile to maintain another class just to not send 45 properties – especially if you might want to send any one of those 45 properties in the future.
                  – Kenny Evitt
                  Jul 17 '13 at 13:01






                • 5




                  @BrendanVogt – I think maybe LukLed's answer helps me understand why these might be useful, particularly that a ViewModel (can) "... combine values from different database entities" [where I'm assuming that the phrase is just as true were "database entities" to be replaced with "Model objects"]. But still, what specific problems were ViewModels intended to address? Do you have any links? I couldn't find anything myself. [And I apologize if I seem to be picking on you!]
                  – Kenny Evitt
                  Jul 17 '13 at 13:09






                • 6




                  +1 for mentioning fluent validation
                  – MUG4N
                  Oct 12 '13 at 17:37






                • 3




                  I'm sorry for being critical but this answer is, unfortunately, incomplete. Defining a viewmodel as only what you need display on your page is like asking "What is a car?" and receiving an answer "Its not an airplane". Well thats true but not very helpful. The more correct definition of a VM is "Everything you need to render your page." If you read down to the bottom I have identified the components you need to build your VM's correctly and easily, in many cases leveraging your existing domain models and presentation models.
                  – Sam
                  May 15 '15 at 16:43















                538














                A view model represents the data that you want to display on your view/page, whether it be used for static text or for input values (like textboxes and dropdown lists) that can be added to the database (or edited). It is something different than your domain model. It is a model for the view.



                Let us say that you have an Employee class that represents your employee domain model and it contains the following properties (unique identifier, first name, last name and date created):



                public class Employee : IEntity

                public int Id get; set;

                public string FirstName get; set;

                public string LastName get; set;

                public DateTime DateCreated get; set;



                View models differ from domain models in that view models only contain the data (represented by properties) that you want to use on your view. For example, lets say that you want to add a new employee record, your view model might look like this:



                public class CreateEmployeeViewModel

                public string FirstName get; set;

                public string LastName get; set;



                As you can see it only contains two of the properties. These two properties are also in the employee domain model. Why is this you may ask? Id might not be set from the view, it might be auto generated by the Employee table. And DateCreated might also be set in the stored procedure or in the service layer of your application. So Id and DateCreated are not needed in the view model. You might want to display these two properties when you view an employee’s details (an employee that has already been captured) as static text.



                When loading the view/page, the create action method in your employee controller will create an instance of this view model, populate any fields if required, and then pass this view model to the view/page:



                public class EmployeeController : Controller

                private readonly IEmployeeService employeeService;

                public EmployeeController(IEmployeeService employeeService)

                this.employeeService = employeeService;


                public ActionResult Create()

                CreateEmployeeViewModel model = new CreateEmployeeViewModel();

                return View(model);


                public ActionResult Create(CreateEmployeeViewModel model)

                // Do what ever needs to be done before adding the employee to the database




                Your view/page might look like this (assuming you are using ASP.NET MVC and the Razor view engine):



                @model MyProject.Web.ViewModels.CreateEmployeeViewModel

                <table>
                <tr>
                <td><b>First Name:</b></td>
                <td>@Html.TextBoxFor(m => m.FirstName, new maxlength = "50", size = "50" )
                @Html.ValidationMessageFor(m => m.FirstName)
                </td>
                </tr>
                <tr>
                <td><b>Last Name:</b></td>
                <td>@Html.TextBoxFor(m => m.LastName, new maxlength = "50", size = "50" )
                @Html.ValidationMessageFor(m => m.LastName)
                </td>
                </tr>
                </table>


                Validation would thus be done only on FirstName and LastName. Using Fluent Validation you might have validation like this:



                public class CreateEmployeeViewModelValidator : AbstractValidator<CreateEmployeeViewModel>

                public CreateEmployeeViewModelValidator()

                RuleFor(m => m.FirstName)
                .NotEmpty()
                .WithMessage("First name required")
                .Length(1, 50)
                .WithMessage("First name must not be greater than 50 characters");

                RuleFor(m => m.LastName)
                .NotEmpty()
                .WithMessage("Last name required")
                .Length(1, 50)
                .WithMessage("Last name must not be greater than 50 characters");




                And with Data Annotations it might look this:



                public class CreateEmployeeViewModel : ViewModelBase

                [Display(Name = "First Name")]
                [Required(ErrorMessage = "First name required")]
                public string FirstName get; set;

                [Display(Name = "Last Name")]
                [Required(ErrorMessage = "Last name required")]
                public string LastName get; set;



                The key thing to remember is that the view model only represents the data that you want to use, nothing else. You can imagine all the unnecessary code and validation if you have a domain model with 30 properties and you only want to update a single value. Given this scenario you would only have this one value/property in the view model and not all the properties that are in the domain object.



                A view model might not only have data from one database table. It can combine data from another table. Take my example above about adding a new employee record. Besides adding just the first and last names you might also want to add the department of the employee. This list of departments will come from your Departments table. So now you have data from the Employees and Departments tables in one view model. You will just then need to add the following two properties to your view model and populate it with data:



                public int DepartmentId get; set; 

                public IEnumerable<Department> Departments get; set;


                When editing employee data (an employee that has already been added to the database) it wouldn’t differ much from my example above. Create a view model, call it for example EditEmployeeViewModel. Only have the data that you want to edit in this view model, like first name and last name. Edit the data and click the submit button. I wouldn’t worry too much about the Id field because the Id value will probably been in the URL, for example:



                http://www.yourwebsite.com/Employee/Edit/3


                Take this Id and pass it through to your repository layer, together with your first name and last name values.



                When deleting a record, I normally follow the same path as with the edit view model. I would also have a URL, for example:



                http://www.yourwebsite.com/Employee/Delete/3


                When the view loads up for the first time I would get the employee’s data from the database using the Id of 3. I would then just display static text on my view/page so that the user can see what employee is being deleted. When the user clicks the Delete button, I would just use the Id value of 3 and pass it to my repository layer. You only need the Id to delete a record from the table.



                Another point, you don’t really need a view model for every action. If it is simple data then it would be fine to only use EmployeeViewModel. If it is complex views/pages and they differ from each other then I would suggest you use separate view models for each.



                I hope this clears up any confusion that you had about view models and domain models.






                share|improve this answer


















                • 5




                  @Kenny: Then show it :) What I was trying to say is lets say you have a domain model with 50 properties and your view only needs to display 5 then it is no use in sending all 50 properties just to display 5.
                  – Brendan Vogt
                  Jul 17 '13 at 5:44






                • 4




                  @BrendanVogt – you did a good job explaining that, but I don't understand what the cost is of "sending all 50 properties". Other code has already created a Model object, with all 50 properties, and it doesn't seem worthwhile to maintain another class just to not send 45 properties – especially if you might want to send any one of those 45 properties in the future.
                  – Kenny Evitt
                  Jul 17 '13 at 13:01






                • 5




                  @BrendanVogt – I think maybe LukLed's answer helps me understand why these might be useful, particularly that a ViewModel (can) "... combine values from different database entities" [where I'm assuming that the phrase is just as true were "database entities" to be replaced with "Model objects"]. But still, what specific problems were ViewModels intended to address? Do you have any links? I couldn't find anything myself. [And I apologize if I seem to be picking on you!]
                  – Kenny Evitt
                  Jul 17 '13 at 13:09






                • 6




                  +1 for mentioning fluent validation
                  – MUG4N
                  Oct 12 '13 at 17:37






                • 3




                  I'm sorry for being critical but this answer is, unfortunately, incomplete. Defining a viewmodel as only what you need display on your page is like asking "What is a car?" and receiving an answer "Its not an airplane". Well thats true but not very helpful. The more correct definition of a VM is "Everything you need to render your page." If you read down to the bottom I have identified the components you need to build your VM's correctly and easily, in many cases leveraging your existing domain models and presentation models.
                  – Sam
                  May 15 '15 at 16:43













                538












                538








                538






                A view model represents the data that you want to display on your view/page, whether it be used for static text or for input values (like textboxes and dropdown lists) that can be added to the database (or edited). It is something different than your domain model. It is a model for the view.



                Let us say that you have an Employee class that represents your employee domain model and it contains the following properties (unique identifier, first name, last name and date created):



                public class Employee : IEntity

                public int Id get; set;

                public string FirstName get; set;

                public string LastName get; set;

                public DateTime DateCreated get; set;



                View models differ from domain models in that view models only contain the data (represented by properties) that you want to use on your view. For example, lets say that you want to add a new employee record, your view model might look like this:



                public class CreateEmployeeViewModel

                public string FirstName get; set;

                public string LastName get; set;



                As you can see it only contains two of the properties. These two properties are also in the employee domain model. Why is this you may ask? Id might not be set from the view, it might be auto generated by the Employee table. And DateCreated might also be set in the stored procedure or in the service layer of your application. So Id and DateCreated are not needed in the view model. You might want to display these two properties when you view an employee’s details (an employee that has already been captured) as static text.



                When loading the view/page, the create action method in your employee controller will create an instance of this view model, populate any fields if required, and then pass this view model to the view/page:



                public class EmployeeController : Controller

                private readonly IEmployeeService employeeService;

                public EmployeeController(IEmployeeService employeeService)

                this.employeeService = employeeService;


                public ActionResult Create()

                CreateEmployeeViewModel model = new CreateEmployeeViewModel();

                return View(model);


                public ActionResult Create(CreateEmployeeViewModel model)

                // Do what ever needs to be done before adding the employee to the database




                Your view/page might look like this (assuming you are using ASP.NET MVC and the Razor view engine):



                @model MyProject.Web.ViewModels.CreateEmployeeViewModel

                <table>
                <tr>
                <td><b>First Name:</b></td>
                <td>@Html.TextBoxFor(m => m.FirstName, new maxlength = "50", size = "50" )
                @Html.ValidationMessageFor(m => m.FirstName)
                </td>
                </tr>
                <tr>
                <td><b>Last Name:</b></td>
                <td>@Html.TextBoxFor(m => m.LastName, new maxlength = "50", size = "50" )
                @Html.ValidationMessageFor(m => m.LastName)
                </td>
                </tr>
                </table>


                Validation would thus be done only on FirstName and LastName. Using Fluent Validation you might have validation like this:



                public class CreateEmployeeViewModelValidator : AbstractValidator<CreateEmployeeViewModel>

                public CreateEmployeeViewModelValidator()

                RuleFor(m => m.FirstName)
                .NotEmpty()
                .WithMessage("First name required")
                .Length(1, 50)
                .WithMessage("First name must not be greater than 50 characters");

                RuleFor(m => m.LastName)
                .NotEmpty()
                .WithMessage("Last name required")
                .Length(1, 50)
                .WithMessage("Last name must not be greater than 50 characters");




                And with Data Annotations it might look this:



                public class CreateEmployeeViewModel : ViewModelBase

                [Display(Name = "First Name")]
                [Required(ErrorMessage = "First name required")]
                public string FirstName get; set;

                [Display(Name = "Last Name")]
                [Required(ErrorMessage = "Last name required")]
                public string LastName get; set;



                The key thing to remember is that the view model only represents the data that you want to use, nothing else. You can imagine all the unnecessary code and validation if you have a domain model with 30 properties and you only want to update a single value. Given this scenario you would only have this one value/property in the view model and not all the properties that are in the domain object.



                A view model might not only have data from one database table. It can combine data from another table. Take my example above about adding a new employee record. Besides adding just the first and last names you might also want to add the department of the employee. This list of departments will come from your Departments table. So now you have data from the Employees and Departments tables in one view model. You will just then need to add the following two properties to your view model and populate it with data:



                public int DepartmentId get; set; 

                public IEnumerable<Department> Departments get; set;


                When editing employee data (an employee that has already been added to the database) it wouldn’t differ much from my example above. Create a view model, call it for example EditEmployeeViewModel. Only have the data that you want to edit in this view model, like first name and last name. Edit the data and click the submit button. I wouldn’t worry too much about the Id field because the Id value will probably been in the URL, for example:



                http://www.yourwebsite.com/Employee/Edit/3


                Take this Id and pass it through to your repository layer, together with your first name and last name values.



                When deleting a record, I normally follow the same path as with the edit view model. I would also have a URL, for example:



                http://www.yourwebsite.com/Employee/Delete/3


                When the view loads up for the first time I would get the employee’s data from the database using the Id of 3. I would then just display static text on my view/page so that the user can see what employee is being deleted. When the user clicks the Delete button, I would just use the Id value of 3 and pass it to my repository layer. You only need the Id to delete a record from the table.



                Another point, you don’t really need a view model for every action. If it is simple data then it would be fine to only use EmployeeViewModel. If it is complex views/pages and they differ from each other then I would suggest you use separate view models for each.



                I hope this clears up any confusion that you had about view models and domain models.






                share|improve this answer














                A view model represents the data that you want to display on your view/page, whether it be used for static text or for input values (like textboxes and dropdown lists) that can be added to the database (or edited). It is something different than your domain model. It is a model for the view.



                Let us say that you have an Employee class that represents your employee domain model and it contains the following properties (unique identifier, first name, last name and date created):



                public class Employee : IEntity

                public int Id get; set;

                public string FirstName get; set;

                public string LastName get; set;

                public DateTime DateCreated get; set;



                View models differ from domain models in that view models only contain the data (represented by properties) that you want to use on your view. For example, lets say that you want to add a new employee record, your view model might look like this:



                public class CreateEmployeeViewModel

                public string FirstName get; set;

                public string LastName get; set;



                As you can see it only contains two of the properties. These two properties are also in the employee domain model. Why is this you may ask? Id might not be set from the view, it might be auto generated by the Employee table. And DateCreated might also be set in the stored procedure or in the service layer of your application. So Id and DateCreated are not needed in the view model. You might want to display these two properties when you view an employee’s details (an employee that has already been captured) as static text.



                When loading the view/page, the create action method in your employee controller will create an instance of this view model, populate any fields if required, and then pass this view model to the view/page:



                public class EmployeeController : Controller

                private readonly IEmployeeService employeeService;

                public EmployeeController(IEmployeeService employeeService)

                this.employeeService = employeeService;


                public ActionResult Create()

                CreateEmployeeViewModel model = new CreateEmployeeViewModel();

                return View(model);


                public ActionResult Create(CreateEmployeeViewModel model)

                // Do what ever needs to be done before adding the employee to the database




                Your view/page might look like this (assuming you are using ASP.NET MVC and the Razor view engine):



                @model MyProject.Web.ViewModels.CreateEmployeeViewModel

                <table>
                <tr>
                <td><b>First Name:</b></td>
                <td>@Html.TextBoxFor(m => m.FirstName, new maxlength = "50", size = "50" )
                @Html.ValidationMessageFor(m => m.FirstName)
                </td>
                </tr>
                <tr>
                <td><b>Last Name:</b></td>
                <td>@Html.TextBoxFor(m => m.LastName, new maxlength = "50", size = "50" )
                @Html.ValidationMessageFor(m => m.LastName)
                </td>
                </tr>
                </table>


                Validation would thus be done only on FirstName and LastName. Using Fluent Validation you might have validation like this:



                public class CreateEmployeeViewModelValidator : AbstractValidator<CreateEmployeeViewModel>

                public CreateEmployeeViewModelValidator()

                RuleFor(m => m.FirstName)
                .NotEmpty()
                .WithMessage("First name required")
                .Length(1, 50)
                .WithMessage("First name must not be greater than 50 characters");

                RuleFor(m => m.LastName)
                .NotEmpty()
                .WithMessage("Last name required")
                .Length(1, 50)
                .WithMessage("Last name must not be greater than 50 characters");




                And with Data Annotations it might look this:



                public class CreateEmployeeViewModel : ViewModelBase

                [Display(Name = "First Name")]
                [Required(ErrorMessage = "First name required")]
                public string FirstName get; set;

                [Display(Name = "Last Name")]
                [Required(ErrorMessage = "Last name required")]
                public string LastName get; set;



                The key thing to remember is that the view model only represents the data that you want to use, nothing else. You can imagine all the unnecessary code and validation if you have a domain model with 30 properties and you only want to update a single value. Given this scenario you would only have this one value/property in the view model and not all the properties that are in the domain object.



                A view model might not only have data from one database table. It can combine data from another table. Take my example above about adding a new employee record. Besides adding just the first and last names you might also want to add the department of the employee. This list of departments will come from your Departments table. So now you have data from the Employees and Departments tables in one view model. You will just then need to add the following two properties to your view model and populate it with data:



                public int DepartmentId get; set; 

                public IEnumerable<Department> Departments get; set;


                When editing employee data (an employee that has already been added to the database) it wouldn’t differ much from my example above. Create a view model, call it for example EditEmployeeViewModel. Only have the data that you want to edit in this view model, like first name and last name. Edit the data and click the submit button. I wouldn’t worry too much about the Id field because the Id value will probably been in the URL, for example:



                http://www.yourwebsite.com/Employee/Edit/3


                Take this Id and pass it through to your repository layer, together with your first name and last name values.



                When deleting a record, I normally follow the same path as with the edit view model. I would also have a URL, for example:



                http://www.yourwebsite.com/Employee/Delete/3


                When the view loads up for the first time I would get the employee’s data from the database using the Id of 3. I would then just display static text on my view/page so that the user can see what employee is being deleted. When the user clicks the Delete button, I would just use the Id value of 3 and pass it to my repository layer. You only need the Id to delete a record from the table.



                Another point, you don’t really need a view model for every action. If it is simple data then it would be fine to only use EmployeeViewModel. If it is complex views/pages and they differ from each other then I would suggest you use separate view models for each.



                I hope this clears up any confusion that you had about view models and domain models.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited May 6 '16 at 11:56

























                answered Jun 17 '12 at 20:21









                Brendan Vogt

                15.3k27119210




                15.3k27119210







                • 5




                  @Kenny: Then show it :) What I was trying to say is lets say you have a domain model with 50 properties and your view only needs to display 5 then it is no use in sending all 50 properties just to display 5.
                  – Brendan Vogt
                  Jul 17 '13 at 5:44






                • 4




                  @BrendanVogt – you did a good job explaining that, but I don't understand what the cost is of "sending all 50 properties". Other code has already created a Model object, with all 50 properties, and it doesn't seem worthwhile to maintain another class just to not send 45 properties – especially if you might want to send any one of those 45 properties in the future.
                  – Kenny Evitt
                  Jul 17 '13 at 13:01






                • 5




                  @BrendanVogt – I think maybe LukLed's answer helps me understand why these might be useful, particularly that a ViewModel (can) "... combine values from different database entities" [where I'm assuming that the phrase is just as true were "database entities" to be replaced with "Model objects"]. But still, what specific problems were ViewModels intended to address? Do you have any links? I couldn't find anything myself. [And I apologize if I seem to be picking on you!]
                  – Kenny Evitt
                  Jul 17 '13 at 13:09






                • 6




                  +1 for mentioning fluent validation
                  – MUG4N
                  Oct 12 '13 at 17:37






                • 3




                  I'm sorry for being critical but this answer is, unfortunately, incomplete. Defining a viewmodel as only what you need display on your page is like asking "What is a car?" and receiving an answer "Its not an airplane". Well thats true but not very helpful. The more correct definition of a VM is "Everything you need to render your page." If you read down to the bottom I have identified the components you need to build your VM's correctly and easily, in many cases leveraging your existing domain models and presentation models.
                  – Sam
                  May 15 '15 at 16:43












                • 5




                  @Kenny: Then show it :) What I was trying to say is lets say you have a domain model with 50 properties and your view only needs to display 5 then it is no use in sending all 50 properties just to display 5.
                  – Brendan Vogt
                  Jul 17 '13 at 5:44






                • 4




                  @BrendanVogt – you did a good job explaining that, but I don't understand what the cost is of "sending all 50 properties". Other code has already created a Model object, with all 50 properties, and it doesn't seem worthwhile to maintain another class just to not send 45 properties – especially if you might want to send any one of those 45 properties in the future.
                  – Kenny Evitt
                  Jul 17 '13 at 13:01






                • 5




                  @BrendanVogt – I think maybe LukLed's answer helps me understand why these might be useful, particularly that a ViewModel (can) "... combine values from different database entities" [where I'm assuming that the phrase is just as true were "database entities" to be replaced with "Model objects"]. But still, what specific problems were ViewModels intended to address? Do you have any links? I couldn't find anything myself. [And I apologize if I seem to be picking on you!]
                  – Kenny Evitt
                  Jul 17 '13 at 13:09






                • 6




                  +1 for mentioning fluent validation
                  – MUG4N
                  Oct 12 '13 at 17:37






                • 3




                  I'm sorry for being critical but this answer is, unfortunately, incomplete. Defining a viewmodel as only what you need display on your page is like asking "What is a car?" and receiving an answer "Its not an airplane". Well thats true but not very helpful. The more correct definition of a VM is "Everything you need to render your page." If you read down to the bottom I have identified the components you need to build your VM's correctly and easily, in many cases leveraging your existing domain models and presentation models.
                  – Sam
                  May 15 '15 at 16:43







                5




                5




                @Kenny: Then show it :) What I was trying to say is lets say you have a domain model with 50 properties and your view only needs to display 5 then it is no use in sending all 50 properties just to display 5.
                – Brendan Vogt
                Jul 17 '13 at 5:44




                @Kenny: Then show it :) What I was trying to say is lets say you have a domain model with 50 properties and your view only needs to display 5 then it is no use in sending all 50 properties just to display 5.
                – Brendan Vogt
                Jul 17 '13 at 5:44




                4




                4




                @BrendanVogt – you did a good job explaining that, but I don't understand what the cost is of "sending all 50 properties". Other code has already created a Model object, with all 50 properties, and it doesn't seem worthwhile to maintain another class just to not send 45 properties – especially if you might want to send any one of those 45 properties in the future.
                – Kenny Evitt
                Jul 17 '13 at 13:01




                @BrendanVogt – you did a good job explaining that, but I don't understand what the cost is of "sending all 50 properties". Other code has already created a Model object, with all 50 properties, and it doesn't seem worthwhile to maintain another class just to not send 45 properties – especially if you might want to send any one of those 45 properties in the future.
                – Kenny Evitt
                Jul 17 '13 at 13:01




                5




                5




                @BrendanVogt – I think maybe LukLed's answer helps me understand why these might be useful, particularly that a ViewModel (can) "... combine values from different database entities" [where I'm assuming that the phrase is just as true were "database entities" to be replaced with "Model objects"]. But still, what specific problems were ViewModels intended to address? Do you have any links? I couldn't find anything myself. [And I apologize if I seem to be picking on you!]
                – Kenny Evitt
                Jul 17 '13 at 13:09




                @BrendanVogt – I think maybe LukLed's answer helps me understand why these might be useful, particularly that a ViewModel (can) "... combine values from different database entities" [where I'm assuming that the phrase is just as true were "database entities" to be replaced with "Model objects"]. But still, what specific problems were ViewModels intended to address? Do you have any links? I couldn't find anything myself. [And I apologize if I seem to be picking on you!]
                – Kenny Evitt
                Jul 17 '13 at 13:09




                6




                6




                +1 for mentioning fluent validation
                – MUG4N
                Oct 12 '13 at 17:37




                +1 for mentioning fluent validation
                – MUG4N
                Oct 12 '13 at 17:37




                3




                3




                I'm sorry for being critical but this answer is, unfortunately, incomplete. Defining a viewmodel as only what you need display on your page is like asking "What is a car?" and receiving an answer "Its not an airplane". Well thats true but not very helpful. The more correct definition of a VM is "Everything you need to render your page." If you read down to the bottom I have identified the components you need to build your VM's correctly and easily, in many cases leveraging your existing domain models and presentation models.
                – Sam
                May 15 '15 at 16:43




                I'm sorry for being critical but this answer is, unfortunately, incomplete. Defining a viewmodel as only what you need display on your page is like asking "What is a car?" and receiving an answer "Its not an airplane". Well thats true but not very helpful. The more correct definition of a VM is "Everything you need to render your page." If you read down to the bottom I have identified the components you need to build your VM's correctly and easily, in many cases leveraging your existing domain models and presentation models.
                – Sam
                May 15 '15 at 16:43













                125














                View model is a class that represents the data model used in a specific view. We could use this class as a model for a login page:



                public class LoginPageVM

                [Required(ErrorMessage = "Are you really trying to login without entering username?")]
                [DisplayName("Username/e-mail")]
                public string UserName get; set;
                [Required(ErrorMessage = "Please enter password:)")]
                [DisplayName("Password")]
                public string Password get; set;
                [DisplayName("Stay logged in when browser is closed")]
                public bool RememberMe get; set;



                Using this view model you can define the view (Razor view engine):



                @model CamelTrap.Models.ViewModels.LoginPageVM

                @using (Html.BeginForm())
                @Html.EditorFor(m => m);
                <input type="submit" value="Save" class="submit" />



                And actions:



                [HttpGet]
                public ActionResult LoginPage()

                return View();


                [HttpPost]
                public ActionResult LoginPage(LoginPageVM model)

                ...code to login user to application...
                return View(model);



                Which produces this result (screen is taken after submitting form, with validation messages):





                As you can see, a view model has many roles:



                • View models documents a view by consisting only fields, that are represented in view.

                • View models may contain specific validation rules using data annotations or IDataErrorInfo.

                • View model defines how a view should look (for LabelFor,EditorFor,DisplayFor helpers).

                • View models can combine values from different database entities.

                • You can specify easily display templates for view models and reuse them in many places using DisplayFor or EditorFor helpers.

                Another example of a view model and its retrieval: We want to display basic user data, his privileges and users name. We create a special view model, which contains only the required fields. We retrieve data from different entities from database, but the view is only aware of the view model class:



                public class UserVM 
                public int ID get; set;
                public string FirstName get; set;
                public string LastName get; set;
                public bool IsAdministrator get; set;
                public string MothersName get; set;



                Retrieval:



                var user = db.userRepository.GetUser(id);

                var model = new UserVM()
                ID = user.ID,
                FirstName = user.FirstName,
                LastName = user.LastName,
                IsAdministrator = user.Proviledges.IsAdministrator,
                MothersName = user.Mother.FirstName + " " + user.Mother.LastName






                share|improve this answer


















                • 4




                  thank you,This is very helpful
                  – unique
                  Jun 16 '12 at 16:30











                • I thin user.Mother.FirstName + " " + user.Mother.LastName should be done in View Model End. All Logic should be done on View Model end.
                  – Kurkula
                  Jun 21 '15 at 16:38






                • 3




                  @Chandana: I believe simple concatenation can be done in view model. There is no reason to expose two fields, if they are meant to be presented together.
                  – LukLed
                  Jun 22 '15 at 12:45















                125














                View model is a class that represents the data model used in a specific view. We could use this class as a model for a login page:



                public class LoginPageVM

                [Required(ErrorMessage = "Are you really trying to login without entering username?")]
                [DisplayName("Username/e-mail")]
                public string UserName get; set;
                [Required(ErrorMessage = "Please enter password:)")]
                [DisplayName("Password")]
                public string Password get; set;
                [DisplayName("Stay logged in when browser is closed")]
                public bool RememberMe get; set;



                Using this view model you can define the view (Razor view engine):



                @model CamelTrap.Models.ViewModels.LoginPageVM

                @using (Html.BeginForm())
                @Html.EditorFor(m => m);
                <input type="submit" value="Save" class="submit" />



                And actions:



                [HttpGet]
                public ActionResult LoginPage()

                return View();


                [HttpPost]
                public ActionResult LoginPage(LoginPageVM model)

                ...code to login user to application...
                return View(model);



                Which produces this result (screen is taken after submitting form, with validation messages):





                As you can see, a view model has many roles:



                • View models documents a view by consisting only fields, that are represented in view.

                • View models may contain specific validation rules using data annotations or IDataErrorInfo.

                • View model defines how a view should look (for LabelFor,EditorFor,DisplayFor helpers).

                • View models can combine values from different database entities.

                • You can specify easily display templates for view models and reuse them in many places using DisplayFor or EditorFor helpers.

                Another example of a view model and its retrieval: We want to display basic user data, his privileges and users name. We create a special view model, which contains only the required fields. We retrieve data from different entities from database, but the view is only aware of the view model class:



                public class UserVM 
                public int ID get; set;
                public string FirstName get; set;
                public string LastName get; set;
                public bool IsAdministrator get; set;
                public string MothersName get; set;



                Retrieval:



                var user = db.userRepository.GetUser(id);

                var model = new UserVM()
                ID = user.ID,
                FirstName = user.FirstName,
                LastName = user.LastName,
                IsAdministrator = user.Proviledges.IsAdministrator,
                MothersName = user.Mother.FirstName + " " + user.Mother.LastName






                share|improve this answer


















                • 4




                  thank you,This is very helpful
                  – unique
                  Jun 16 '12 at 16:30











                • I thin user.Mother.FirstName + " " + user.Mother.LastName should be done in View Model End. All Logic should be done on View Model end.
                  – Kurkula
                  Jun 21 '15 at 16:38






                • 3




                  @Chandana: I believe simple concatenation can be done in view model. There is no reason to expose two fields, if they are meant to be presented together.
                  – LukLed
                  Jun 22 '15 at 12:45













                125












                125








                125






                View model is a class that represents the data model used in a specific view. We could use this class as a model for a login page:



                public class LoginPageVM

                [Required(ErrorMessage = "Are you really trying to login without entering username?")]
                [DisplayName("Username/e-mail")]
                public string UserName get; set;
                [Required(ErrorMessage = "Please enter password:)")]
                [DisplayName("Password")]
                public string Password get; set;
                [DisplayName("Stay logged in when browser is closed")]
                public bool RememberMe get; set;



                Using this view model you can define the view (Razor view engine):



                @model CamelTrap.Models.ViewModels.LoginPageVM

                @using (Html.BeginForm())
                @Html.EditorFor(m => m);
                <input type="submit" value="Save" class="submit" />



                And actions:



                [HttpGet]
                public ActionResult LoginPage()

                return View();


                [HttpPost]
                public ActionResult LoginPage(LoginPageVM model)

                ...code to login user to application...
                return View(model);



                Which produces this result (screen is taken after submitting form, with validation messages):





                As you can see, a view model has many roles:



                • View models documents a view by consisting only fields, that are represented in view.

                • View models may contain specific validation rules using data annotations or IDataErrorInfo.

                • View model defines how a view should look (for LabelFor,EditorFor,DisplayFor helpers).

                • View models can combine values from different database entities.

                • You can specify easily display templates for view models and reuse them in many places using DisplayFor or EditorFor helpers.

                Another example of a view model and its retrieval: We want to display basic user data, his privileges and users name. We create a special view model, which contains only the required fields. We retrieve data from different entities from database, but the view is only aware of the view model class:



                public class UserVM 
                public int ID get; set;
                public string FirstName get; set;
                public string LastName get; set;
                public bool IsAdministrator get; set;
                public string MothersName get; set;



                Retrieval:



                var user = db.userRepository.GetUser(id);

                var model = new UserVM()
                ID = user.ID,
                FirstName = user.FirstName,
                LastName = user.LastName,
                IsAdministrator = user.Proviledges.IsAdministrator,
                MothersName = user.Mother.FirstName + " " + user.Mother.LastName






                share|improve this answer














                View model is a class that represents the data model used in a specific view. We could use this class as a model for a login page:



                public class LoginPageVM

                [Required(ErrorMessage = "Are you really trying to login without entering username?")]
                [DisplayName("Username/e-mail")]
                public string UserName get; set;
                [Required(ErrorMessage = "Please enter password:)")]
                [DisplayName("Password")]
                public string Password get; set;
                [DisplayName("Stay logged in when browser is closed")]
                public bool RememberMe get; set;



                Using this view model you can define the view (Razor view engine):



                @model CamelTrap.Models.ViewModels.LoginPageVM

                @using (Html.BeginForm())
                @Html.EditorFor(m => m);
                <input type="submit" value="Save" class="submit" />



                And actions:



                [HttpGet]
                public ActionResult LoginPage()

                return View();


                [HttpPost]
                public ActionResult LoginPage(LoginPageVM model)

                ...code to login user to application...
                return View(model);



                Which produces this result (screen is taken after submitting form, with validation messages):





                As you can see, a view model has many roles:



                • View models documents a view by consisting only fields, that are represented in view.

                • View models may contain specific validation rules using data annotations or IDataErrorInfo.

                • View model defines how a view should look (for LabelFor,EditorFor,DisplayFor helpers).

                • View models can combine values from different database entities.

                • You can specify easily display templates for view models and reuse them in many places using DisplayFor or EditorFor helpers.

                Another example of a view model and its retrieval: We want to display basic user data, his privileges and users name. We create a special view model, which contains only the required fields. We retrieve data from different entities from database, but the view is only aware of the view model class:



                public class UserVM 
                public int ID get; set;
                public string FirstName get; set;
                public string LastName get; set;
                public bool IsAdministrator get; set;
                public string MothersName get; set;



                Retrieval:



                var user = db.userRepository.GetUser(id);

                var model = new UserVM()
                ID = user.ID,
                FirstName = user.FirstName,
                LastName = user.LastName,
                IsAdministrator = user.Proviledges.IsAdministrator,
                MothersName = user.Mother.FirstName + " " + user.Mother.LastName







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Aug 20 '14 at 19:09









                VMai

                8,83261630




                8,83261630










                answered Jun 16 '12 at 14:41









                LukLed

                26.2k1672100




                26.2k1672100







                • 4




                  thank you,This is very helpful
                  – unique
                  Jun 16 '12 at 16:30











                • I thin user.Mother.FirstName + " " + user.Mother.LastName should be done in View Model End. All Logic should be done on View Model end.
                  – Kurkula
                  Jun 21 '15 at 16:38






                • 3




                  @Chandana: I believe simple concatenation can be done in view model. There is no reason to expose two fields, if they are meant to be presented together.
                  – LukLed
                  Jun 22 '15 at 12:45












                • 4




                  thank you,This is very helpful
                  – unique
                  Jun 16 '12 at 16:30











                • I thin user.Mother.FirstName + " " + user.Mother.LastName should be done in View Model End. All Logic should be done on View Model end.
                  – Kurkula
                  Jun 21 '15 at 16:38






                • 3




                  @Chandana: I believe simple concatenation can be done in view model. There is no reason to expose two fields, if they are meant to be presented together.
                  – LukLed
                  Jun 22 '15 at 12:45







                4




                4




                thank you,This is very helpful
                – unique
                Jun 16 '12 at 16:30





                thank you,This is very helpful
                – unique
                Jun 16 '12 at 16:30













                I thin user.Mother.FirstName + " " + user.Mother.LastName should be done in View Model End. All Logic should be done on View Model end.
                – Kurkula
                Jun 21 '15 at 16:38




                I thin user.Mother.FirstName + " " + user.Mother.LastName should be done in View Model End. All Logic should be done on View Model end.
                – Kurkula
                Jun 21 '15 at 16:38




                3




                3




                @Chandana: I believe simple concatenation can be done in view model. There is no reason to expose two fields, if they are meant to be presented together.
                – LukLed
                Jun 22 '15 at 12:45




                @Chandana: I believe simple concatenation can be done in view model. There is no reason to expose two fields, if they are meant to be presented together.
                – LukLed
                Jun 22 '15 at 12:45











                68














                Edit: I updated this answer on my Blog:



                http://www.samwheat.com/Post/The-function-of-ViewModels-in-MVC-web-development



                My answer is a bit lengthy but I think it is important to compare view models to other types of commonly used models to understand why they are different and why they are necessary.



                To summarize, and to directly answer the question that is asked:



                Generally speaking, a view model is an object that contains all the properties and methods necessary to render a view. View model properties are often related to data objects such as customers and orders and in addition they also contain properties related to the page or application itself such as user name, application name etc. View models provide a convenient object to pass to a rendering engine to create a html page. One of many reasons to use a view model is that view models provide a way to unit test certain presentation tasks such as handling user input, validating data, retrieving data for display, etc.



                Here is a comparison of Entity models (a.ka. DTO's a.ka. models), Presentation Models, and View Models.



                Data Transfer Objects a.k.a “Model”



                A Data Transfer Object (DTO) is a class with properties that match a table schema in a database. DTO’s are named for their common usage for shuttling data to and from a data store.

                Characteristics of DTO’s:



                • Are business objects – their definition is dependent on application data.



                • Usually contain properties only – no code.



                • Primarily used for transporting data to and from a database.



                • Properties exactly or closely match fields on a specific table in a data store.



                Database tables are usually normalized therefore DTO’s are usually normalized also. This makes them of limited use for presenting data. However, for certain simple data structures they often do quite well.



                Here are two examples of what DTO’s might look like:



                public class Customer

                public int ID get; set;
                public string CustomerName get; set;



                public class Order

                public int ID get; set;
                public int CustomerID get; set;
                public DateTime OrderDate get; set;
                public Decimal OrderAmount get; set;





                Presentation Models



                A presentation model is a utility class that is used to render data on a screen or report. Presentation models are typically used to model complex data structures that are composed from data from multiple DTO’s. Presentation models often represent a denormalized view of data.



                Characteristics of Presentation Models:



                • Are business objects – their definition is dependent on application data.



                • Contain mostly properties. Code is typically limited to formatting data or converting to or from a DTO. Presentation Models should not contain business logic.



                • Often present a denormalized view of data. That is, they often combine properties from multiple DTO’s.



                • Often contain properties of a different base type than a DTO. For example dollar amounts may be represented as strings so they can contain commas and a currency symbol.



                • Often defined by how they are used as well as their object characteristics. In other words, a simple DTO that is used as the backing model for rendering a grid is in fact also a presentation model in the context of that grid.



                Presentation models are used “as needed” and “where needed” (whereas DTO’s are usually tied to the database schema). A presentation model may be used to model data for an entire page, a grid on a page, or a dropdown on a grid on a page. Presentation models often contain properties that are other presentation models. Presentation models are often constructed for a single-use purpose such as to render a specific grid on a single page.



                An example presentation model:



                public class PresentationOrder

                public int OrderID get; set;
                public DateTime OrderDate get; set;
                public string PrettyDate get return OrderDate.ToShortDateString();
                public string CustomerName get; set;
                public Decimal OrderAmount get; set;
                public string PrettyAmount get return string.Format("0:C", OrderAmount);



                View Models



                A view model is similar to a presentation model in that is a backing class for rendering a view. However it is very different from a Presentation Model or a DTO in how it is constructed. View models often contain the same properties as presentation models and DTO’s and for this reason they are often confused one for the other.



                Characteristics of View Models:



                • Are the single source of data used to render a page or screen. Usually this means that a view model will expose every property that any control on the page will need to render itself correctly. Making the view model the single source of data for the view greatly improves its capability and value for unit testing.



                • Are composite objects that contain properties that consist of application data as well as properties that are used by application code. This characteristic is crucial when designing the view model for reusability and is discussed in the examples below.



                • Contain application code. View Models usually contain methods that are called during rendering and when the user is interacting with the page. This code typically relates to event handling, animation, visibility of controls, styling, etc.



                • Contain code that calls business services for the purpose of retrieving data or sending it to a database server. This code is often mistakenly placed in a controller. Calling business services from a controller usually limits the usefulness of the view model for unit testing. To be clear, view models themselves should not contain business logic but should make calls to services which do contain business logic.



                • Often contain properties which are other view models for other pages or screens.



                • Are written “per page” or “per screen”. A unique View Model is typically written for every page or screen in an application.



                • Usually derive from a base class since most pages and screens share common properties.



                View Model Composition



                As stated earlier, view models are composite objects in that they combine application properties and business data properties on a single object. Examples of commonly used application properties that are used on view models are:



                • Properties that are used to display application state such as error messages, user name, status, etc.



                • Properties used to format, display, stylize, or animate controls.



                • Properties used for data binding such as list objects and properties that hold intermediate data that is input by the user.



                The following examples show why the composite nature of view models is important and how we can best construct a View Model that efficient and reusable.



                Assume we are writing a web application. One of the requirements of the application design is that the page title, user name, and application name must be displayed on every page. If we want to create a page to display a presentation order object, we may modify the presentation model as follows:



                public class PresentationOrder

                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;
                public int OrderID get; set;
                public DateTime OrderDate get; set;
                public string PrettyDate get return OrderDate.ToShortDateString();
                public string CustomerName get; set;
                public Decimal OrderAmount get; set;
                public string PrettyAmount get return string.Format("0:C", OrderAmount);



                This design might work… but what if we want to create a page that will display a list of orders? The PageTitle, UserName, and ApplicationName properties will be repeated and become unwieldy to work with. Also, what if we want to define some page-level logic in the constructor of the class? We can no longer do that if we create an instance for every order that will be displayed.



                Composition over inheritance



                Here is a way we might re-factor the order presentation model such that it become a true view model and will be useful for displaying a single PresentationOrder object or a collection of PresentationOrder objects:



                public class PresentationOrderVM

                // Application properties
                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;

                // Business properties
                public PresentationOrder Order get; set;



                public class PresentationOrderVM

                // Application properties
                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;

                // Business properties
                public List<PresentationOrder> Orders get; set;



                Looking at the above two classes we can see that one way to think about a view model is that it is a presentation model that contains another presentation model as a property. The top level presentation model (i.e. view model) contains properties that are relevant to the page or application while presentation model (property) contains properties that are relevant to application data.



                We can take our design a step further and create a base view model class that can be used not only for PresentationOrders, but for any other class as well:



                public class BaseViewModel

                // Application properties
                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;



                Now we can simplify our PresentationOrderVM like this:



                public class PresentationOrderVM : BaseViewModel

                // Business properties
                public PresentationOrder Order get; set;


                public class PresentationOrderVM : BaseViewModel

                // Business properties
                public List<PresentationOrder> Orders get; set;



                We can make our BaseViewModel even more re-usable by making it generic:



                public class BaseViewModel<T>

                // Application properties
                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;

                // Business property
                public T BusinessObject get; set;



                Now our implementations are effortless:



                public class PresentationOrderVM : BaseViewModel<PresentationOrder>

                // done!


                public class PresentationOrderVM : BaseViewModel<List<PresentationOrder>>

                // done!






                share|improve this answer


















                • 1




                  Sam Thank You!! this helped me fully grasp the multi-faceted entity that is a: View-Model. I'm a college student just learning the MVC architecture, and this clarified a bunch of the capable functionalities that are exposed to the developer. If I could I would put a star next to your answer.
                  – Chef_Code
                  Jan 26 '16 at 3:13







                • 1




                  @Sam 'View models often contain the same properties as presentation models and DTO’s and for this reason they are often confused one for the other.' Does that mean they're commonly used instead of presentation models, or are they meant to contain the presentation models/dtos?
                  – Alexander Derck
                  Feb 1 '17 at 8:24






                • 2




                  @AlexanderDerck They are used for different purposes. They are confused one for the other (in error). No, you typically will not use a pres model in place of a view model. Much more common is that the VM "contains" the presentation model i.e. MyViewModel<MyPresModel>
                  – Sam
                  Feb 1 '17 at 15:05






                • 1




                  Way cool Sam! Thanks
                  – Stokely
                  Jul 13 '17 at 23:48






                • 1




                  @Sam Assuming model objects are live objects e.g. nhibernate models.. so by having BusinessObject aren't we exposing model/live objects directly to the view? i.e. the business object can be used to modify the database state directly? Also, what about nested view models? That would require multiple business object properties, right?
                  – Muhammad Ali
                  Sep 30 '17 at 9:54
















                68














                Edit: I updated this answer on my Blog:



                http://www.samwheat.com/Post/The-function-of-ViewModels-in-MVC-web-development



                My answer is a bit lengthy but I think it is important to compare view models to other types of commonly used models to understand why they are different and why they are necessary.



                To summarize, and to directly answer the question that is asked:



                Generally speaking, a view model is an object that contains all the properties and methods necessary to render a view. View model properties are often related to data objects such as customers and orders and in addition they also contain properties related to the page or application itself such as user name, application name etc. View models provide a convenient object to pass to a rendering engine to create a html page. One of many reasons to use a view model is that view models provide a way to unit test certain presentation tasks such as handling user input, validating data, retrieving data for display, etc.



                Here is a comparison of Entity models (a.ka. DTO's a.ka. models), Presentation Models, and View Models.



                Data Transfer Objects a.k.a “Model”



                A Data Transfer Object (DTO) is a class with properties that match a table schema in a database. DTO’s are named for their common usage for shuttling data to and from a data store.

                Characteristics of DTO’s:



                • Are business objects – their definition is dependent on application data.



                • Usually contain properties only – no code.



                • Primarily used for transporting data to and from a database.



                • Properties exactly or closely match fields on a specific table in a data store.



                Database tables are usually normalized therefore DTO’s are usually normalized also. This makes them of limited use for presenting data. However, for certain simple data structures they often do quite well.



                Here are two examples of what DTO’s might look like:



                public class Customer

                public int ID get; set;
                public string CustomerName get; set;



                public class Order

                public int ID get; set;
                public int CustomerID get; set;
                public DateTime OrderDate get; set;
                public Decimal OrderAmount get; set;





                Presentation Models



                A presentation model is a utility class that is used to render data on a screen or report. Presentation models are typically used to model complex data structures that are composed from data from multiple DTO’s. Presentation models often represent a denormalized view of data.



                Characteristics of Presentation Models:



                • Are business objects – their definition is dependent on application data.



                • Contain mostly properties. Code is typically limited to formatting data or converting to or from a DTO. Presentation Models should not contain business logic.



                • Often present a denormalized view of data. That is, they often combine properties from multiple DTO’s.



                • Often contain properties of a different base type than a DTO. For example dollar amounts may be represented as strings so they can contain commas and a currency symbol.



                • Often defined by how they are used as well as their object characteristics. In other words, a simple DTO that is used as the backing model for rendering a grid is in fact also a presentation model in the context of that grid.



                Presentation models are used “as needed” and “where needed” (whereas DTO’s are usually tied to the database schema). A presentation model may be used to model data for an entire page, a grid on a page, or a dropdown on a grid on a page. Presentation models often contain properties that are other presentation models. Presentation models are often constructed for a single-use purpose such as to render a specific grid on a single page.



                An example presentation model:



                public class PresentationOrder

                public int OrderID get; set;
                public DateTime OrderDate get; set;
                public string PrettyDate get return OrderDate.ToShortDateString();
                public string CustomerName get; set;
                public Decimal OrderAmount get; set;
                public string PrettyAmount get return string.Format("0:C", OrderAmount);



                View Models



                A view model is similar to a presentation model in that is a backing class for rendering a view. However it is very different from a Presentation Model or a DTO in how it is constructed. View models often contain the same properties as presentation models and DTO’s and for this reason they are often confused one for the other.



                Characteristics of View Models:



                • Are the single source of data used to render a page or screen. Usually this means that a view model will expose every property that any control on the page will need to render itself correctly. Making the view model the single source of data for the view greatly improves its capability and value for unit testing.



                • Are composite objects that contain properties that consist of application data as well as properties that are used by application code. This characteristic is crucial when designing the view model for reusability and is discussed in the examples below.



                • Contain application code. View Models usually contain methods that are called during rendering and when the user is interacting with the page. This code typically relates to event handling, animation, visibility of controls, styling, etc.



                • Contain code that calls business services for the purpose of retrieving data or sending it to a database server. This code is often mistakenly placed in a controller. Calling business services from a controller usually limits the usefulness of the view model for unit testing. To be clear, view models themselves should not contain business logic but should make calls to services which do contain business logic.



                • Often contain properties which are other view models for other pages or screens.



                • Are written “per page” or “per screen”. A unique View Model is typically written for every page or screen in an application.



                • Usually derive from a base class since most pages and screens share common properties.



                View Model Composition



                As stated earlier, view models are composite objects in that they combine application properties and business data properties on a single object. Examples of commonly used application properties that are used on view models are:



                • Properties that are used to display application state such as error messages, user name, status, etc.



                • Properties used to format, display, stylize, or animate controls.



                • Properties used for data binding such as list objects and properties that hold intermediate data that is input by the user.



                The following examples show why the composite nature of view models is important and how we can best construct a View Model that efficient and reusable.



                Assume we are writing a web application. One of the requirements of the application design is that the page title, user name, and application name must be displayed on every page. If we want to create a page to display a presentation order object, we may modify the presentation model as follows:



                public class PresentationOrder

                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;
                public int OrderID get; set;
                public DateTime OrderDate get; set;
                public string PrettyDate get return OrderDate.ToShortDateString();
                public string CustomerName get; set;
                public Decimal OrderAmount get; set;
                public string PrettyAmount get return string.Format("0:C", OrderAmount);



                This design might work… but what if we want to create a page that will display a list of orders? The PageTitle, UserName, and ApplicationName properties will be repeated and become unwieldy to work with. Also, what if we want to define some page-level logic in the constructor of the class? We can no longer do that if we create an instance for every order that will be displayed.



                Composition over inheritance



                Here is a way we might re-factor the order presentation model such that it become a true view model and will be useful for displaying a single PresentationOrder object or a collection of PresentationOrder objects:



                public class PresentationOrderVM

                // Application properties
                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;

                // Business properties
                public PresentationOrder Order get; set;



                public class PresentationOrderVM

                // Application properties
                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;

                // Business properties
                public List<PresentationOrder> Orders get; set;



                Looking at the above two classes we can see that one way to think about a view model is that it is a presentation model that contains another presentation model as a property. The top level presentation model (i.e. view model) contains properties that are relevant to the page or application while presentation model (property) contains properties that are relevant to application data.



                We can take our design a step further and create a base view model class that can be used not only for PresentationOrders, but for any other class as well:



                public class BaseViewModel

                // Application properties
                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;



                Now we can simplify our PresentationOrderVM like this:



                public class PresentationOrderVM : BaseViewModel

                // Business properties
                public PresentationOrder Order get; set;


                public class PresentationOrderVM : BaseViewModel

                // Business properties
                public List<PresentationOrder> Orders get; set;



                We can make our BaseViewModel even more re-usable by making it generic:



                public class BaseViewModel<T>

                // Application properties
                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;

                // Business property
                public T BusinessObject get; set;



                Now our implementations are effortless:



                public class PresentationOrderVM : BaseViewModel<PresentationOrder>

                // done!


                public class PresentationOrderVM : BaseViewModel<List<PresentationOrder>>

                // done!






                share|improve this answer


















                • 1




                  Sam Thank You!! this helped me fully grasp the multi-faceted entity that is a: View-Model. I'm a college student just learning the MVC architecture, and this clarified a bunch of the capable functionalities that are exposed to the developer. If I could I would put a star next to your answer.
                  – Chef_Code
                  Jan 26 '16 at 3:13







                • 1




                  @Sam 'View models often contain the same properties as presentation models and DTO’s and for this reason they are often confused one for the other.' Does that mean they're commonly used instead of presentation models, or are they meant to contain the presentation models/dtos?
                  – Alexander Derck
                  Feb 1 '17 at 8:24






                • 2




                  @AlexanderDerck They are used for different purposes. They are confused one for the other (in error). No, you typically will not use a pres model in place of a view model. Much more common is that the VM "contains" the presentation model i.e. MyViewModel<MyPresModel>
                  – Sam
                  Feb 1 '17 at 15:05






                • 1




                  Way cool Sam! Thanks
                  – Stokely
                  Jul 13 '17 at 23:48






                • 1




                  @Sam Assuming model objects are live objects e.g. nhibernate models.. so by having BusinessObject aren't we exposing model/live objects directly to the view? i.e. the business object can be used to modify the database state directly? Also, what about nested view models? That would require multiple business object properties, right?
                  – Muhammad Ali
                  Sep 30 '17 at 9:54














                68












                68








                68






                Edit: I updated this answer on my Blog:



                http://www.samwheat.com/Post/The-function-of-ViewModels-in-MVC-web-development



                My answer is a bit lengthy but I think it is important to compare view models to other types of commonly used models to understand why they are different and why they are necessary.



                To summarize, and to directly answer the question that is asked:



                Generally speaking, a view model is an object that contains all the properties and methods necessary to render a view. View model properties are often related to data objects such as customers and orders and in addition they also contain properties related to the page or application itself such as user name, application name etc. View models provide a convenient object to pass to a rendering engine to create a html page. One of many reasons to use a view model is that view models provide a way to unit test certain presentation tasks such as handling user input, validating data, retrieving data for display, etc.



                Here is a comparison of Entity models (a.ka. DTO's a.ka. models), Presentation Models, and View Models.



                Data Transfer Objects a.k.a “Model”



                A Data Transfer Object (DTO) is a class with properties that match a table schema in a database. DTO’s are named for their common usage for shuttling data to and from a data store.

                Characteristics of DTO’s:



                • Are business objects – their definition is dependent on application data.



                • Usually contain properties only – no code.



                • Primarily used for transporting data to and from a database.



                • Properties exactly or closely match fields on a specific table in a data store.



                Database tables are usually normalized therefore DTO’s are usually normalized also. This makes them of limited use for presenting data. However, for certain simple data structures they often do quite well.



                Here are two examples of what DTO’s might look like:



                public class Customer

                public int ID get; set;
                public string CustomerName get; set;



                public class Order

                public int ID get; set;
                public int CustomerID get; set;
                public DateTime OrderDate get; set;
                public Decimal OrderAmount get; set;





                Presentation Models



                A presentation model is a utility class that is used to render data on a screen or report. Presentation models are typically used to model complex data structures that are composed from data from multiple DTO’s. Presentation models often represent a denormalized view of data.



                Characteristics of Presentation Models:



                • Are business objects – their definition is dependent on application data.



                • Contain mostly properties. Code is typically limited to formatting data or converting to or from a DTO. Presentation Models should not contain business logic.



                • Often present a denormalized view of data. That is, they often combine properties from multiple DTO’s.



                • Often contain properties of a different base type than a DTO. For example dollar amounts may be represented as strings so they can contain commas and a currency symbol.



                • Often defined by how they are used as well as their object characteristics. In other words, a simple DTO that is used as the backing model for rendering a grid is in fact also a presentation model in the context of that grid.



                Presentation models are used “as needed” and “where needed” (whereas DTO’s are usually tied to the database schema). A presentation model may be used to model data for an entire page, a grid on a page, or a dropdown on a grid on a page. Presentation models often contain properties that are other presentation models. Presentation models are often constructed for a single-use purpose such as to render a specific grid on a single page.



                An example presentation model:



                public class PresentationOrder

                public int OrderID get; set;
                public DateTime OrderDate get; set;
                public string PrettyDate get return OrderDate.ToShortDateString();
                public string CustomerName get; set;
                public Decimal OrderAmount get; set;
                public string PrettyAmount get return string.Format("0:C", OrderAmount);



                View Models



                A view model is similar to a presentation model in that is a backing class for rendering a view. However it is very different from a Presentation Model or a DTO in how it is constructed. View models often contain the same properties as presentation models and DTO’s and for this reason they are often confused one for the other.



                Characteristics of View Models:



                • Are the single source of data used to render a page or screen. Usually this means that a view model will expose every property that any control on the page will need to render itself correctly. Making the view model the single source of data for the view greatly improves its capability and value for unit testing.



                • Are composite objects that contain properties that consist of application data as well as properties that are used by application code. This characteristic is crucial when designing the view model for reusability and is discussed in the examples below.



                • Contain application code. View Models usually contain methods that are called during rendering and when the user is interacting with the page. This code typically relates to event handling, animation, visibility of controls, styling, etc.



                • Contain code that calls business services for the purpose of retrieving data or sending it to a database server. This code is often mistakenly placed in a controller. Calling business services from a controller usually limits the usefulness of the view model for unit testing. To be clear, view models themselves should not contain business logic but should make calls to services which do contain business logic.



                • Often contain properties which are other view models for other pages or screens.



                • Are written “per page” or “per screen”. A unique View Model is typically written for every page or screen in an application.



                • Usually derive from a base class since most pages and screens share common properties.



                View Model Composition



                As stated earlier, view models are composite objects in that they combine application properties and business data properties on a single object. Examples of commonly used application properties that are used on view models are:



                • Properties that are used to display application state such as error messages, user name, status, etc.



                • Properties used to format, display, stylize, or animate controls.



                • Properties used for data binding such as list objects and properties that hold intermediate data that is input by the user.



                The following examples show why the composite nature of view models is important and how we can best construct a View Model that efficient and reusable.



                Assume we are writing a web application. One of the requirements of the application design is that the page title, user name, and application name must be displayed on every page. If we want to create a page to display a presentation order object, we may modify the presentation model as follows:



                public class PresentationOrder

                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;
                public int OrderID get; set;
                public DateTime OrderDate get; set;
                public string PrettyDate get return OrderDate.ToShortDateString();
                public string CustomerName get; set;
                public Decimal OrderAmount get; set;
                public string PrettyAmount get return string.Format("0:C", OrderAmount);



                This design might work… but what if we want to create a page that will display a list of orders? The PageTitle, UserName, and ApplicationName properties will be repeated and become unwieldy to work with. Also, what if we want to define some page-level logic in the constructor of the class? We can no longer do that if we create an instance for every order that will be displayed.



                Composition over inheritance



                Here is a way we might re-factor the order presentation model such that it become a true view model and will be useful for displaying a single PresentationOrder object or a collection of PresentationOrder objects:



                public class PresentationOrderVM

                // Application properties
                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;

                // Business properties
                public PresentationOrder Order get; set;



                public class PresentationOrderVM

                // Application properties
                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;

                // Business properties
                public List<PresentationOrder> Orders get; set;



                Looking at the above two classes we can see that one way to think about a view model is that it is a presentation model that contains another presentation model as a property. The top level presentation model (i.e. view model) contains properties that are relevant to the page or application while presentation model (property) contains properties that are relevant to application data.



                We can take our design a step further and create a base view model class that can be used not only for PresentationOrders, but for any other class as well:



                public class BaseViewModel

                // Application properties
                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;



                Now we can simplify our PresentationOrderVM like this:



                public class PresentationOrderVM : BaseViewModel

                // Business properties
                public PresentationOrder Order get; set;


                public class PresentationOrderVM : BaseViewModel

                // Business properties
                public List<PresentationOrder> Orders get; set;



                We can make our BaseViewModel even more re-usable by making it generic:



                public class BaseViewModel<T>

                // Application properties
                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;

                // Business property
                public T BusinessObject get; set;



                Now our implementations are effortless:



                public class PresentationOrderVM : BaseViewModel<PresentationOrder>

                // done!


                public class PresentationOrderVM : BaseViewModel<List<PresentationOrder>>

                // done!






                share|improve this answer














                Edit: I updated this answer on my Blog:



                http://www.samwheat.com/Post/The-function-of-ViewModels-in-MVC-web-development



                My answer is a bit lengthy but I think it is important to compare view models to other types of commonly used models to understand why they are different and why they are necessary.



                To summarize, and to directly answer the question that is asked:



                Generally speaking, a view model is an object that contains all the properties and methods necessary to render a view. View model properties are often related to data objects such as customers and orders and in addition they also contain properties related to the page or application itself such as user name, application name etc. View models provide a convenient object to pass to a rendering engine to create a html page. One of many reasons to use a view model is that view models provide a way to unit test certain presentation tasks such as handling user input, validating data, retrieving data for display, etc.



                Here is a comparison of Entity models (a.ka. DTO's a.ka. models), Presentation Models, and View Models.



                Data Transfer Objects a.k.a “Model”



                A Data Transfer Object (DTO) is a class with properties that match a table schema in a database. DTO’s are named for their common usage for shuttling data to and from a data store.

                Characteristics of DTO’s:



                • Are business objects – their definition is dependent on application data.



                • Usually contain properties only – no code.



                • Primarily used for transporting data to and from a database.



                • Properties exactly or closely match fields on a specific table in a data store.



                Database tables are usually normalized therefore DTO’s are usually normalized also. This makes them of limited use for presenting data. However, for certain simple data structures they often do quite well.



                Here are two examples of what DTO’s might look like:



                public class Customer

                public int ID get; set;
                public string CustomerName get; set;



                public class Order

                public int ID get; set;
                public int CustomerID get; set;
                public DateTime OrderDate get; set;
                public Decimal OrderAmount get; set;





                Presentation Models



                A presentation model is a utility class that is used to render data on a screen or report. Presentation models are typically used to model complex data structures that are composed from data from multiple DTO’s. Presentation models often represent a denormalized view of data.



                Characteristics of Presentation Models:



                • Are business objects – their definition is dependent on application data.



                • Contain mostly properties. Code is typically limited to formatting data or converting to or from a DTO. Presentation Models should not contain business logic.



                • Often present a denormalized view of data. That is, they often combine properties from multiple DTO’s.



                • Often contain properties of a different base type than a DTO. For example dollar amounts may be represented as strings so they can contain commas and a currency symbol.



                • Often defined by how they are used as well as their object characteristics. In other words, a simple DTO that is used as the backing model for rendering a grid is in fact also a presentation model in the context of that grid.



                Presentation models are used “as needed” and “where needed” (whereas DTO’s are usually tied to the database schema). A presentation model may be used to model data for an entire page, a grid on a page, or a dropdown on a grid on a page. Presentation models often contain properties that are other presentation models. Presentation models are often constructed for a single-use purpose such as to render a specific grid on a single page.



                An example presentation model:



                public class PresentationOrder

                public int OrderID get; set;
                public DateTime OrderDate get; set;
                public string PrettyDate get return OrderDate.ToShortDateString();
                public string CustomerName get; set;
                public Decimal OrderAmount get; set;
                public string PrettyAmount get return string.Format("0:C", OrderAmount);



                View Models



                A view model is similar to a presentation model in that is a backing class for rendering a view. However it is very different from a Presentation Model or a DTO in how it is constructed. View models often contain the same properties as presentation models and DTO’s and for this reason they are often confused one for the other.



                Characteristics of View Models:



                • Are the single source of data used to render a page or screen. Usually this means that a view model will expose every property that any control on the page will need to render itself correctly. Making the view model the single source of data for the view greatly improves its capability and value for unit testing.



                • Are composite objects that contain properties that consist of application data as well as properties that are used by application code. This characteristic is crucial when designing the view model for reusability and is discussed in the examples below.



                • Contain application code. View Models usually contain methods that are called during rendering and when the user is interacting with the page. This code typically relates to event handling, animation, visibility of controls, styling, etc.



                • Contain code that calls business services for the purpose of retrieving data or sending it to a database server. This code is often mistakenly placed in a controller. Calling business services from a controller usually limits the usefulness of the view model for unit testing. To be clear, view models themselves should not contain business logic but should make calls to services which do contain business logic.



                • Often contain properties which are other view models for other pages or screens.



                • Are written “per page” or “per screen”. A unique View Model is typically written for every page or screen in an application.



                • Usually derive from a base class since most pages and screens share common properties.



                View Model Composition



                As stated earlier, view models are composite objects in that they combine application properties and business data properties on a single object. Examples of commonly used application properties that are used on view models are:



                • Properties that are used to display application state such as error messages, user name, status, etc.



                • Properties used to format, display, stylize, or animate controls.



                • Properties used for data binding such as list objects and properties that hold intermediate data that is input by the user.



                The following examples show why the composite nature of view models is important and how we can best construct a View Model that efficient and reusable.



                Assume we are writing a web application. One of the requirements of the application design is that the page title, user name, and application name must be displayed on every page. If we want to create a page to display a presentation order object, we may modify the presentation model as follows:



                public class PresentationOrder

                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;
                public int OrderID get; set;
                public DateTime OrderDate get; set;
                public string PrettyDate get return OrderDate.ToShortDateString();
                public string CustomerName get; set;
                public Decimal OrderAmount get; set;
                public string PrettyAmount get return string.Format("0:C", OrderAmount);



                This design might work… but what if we want to create a page that will display a list of orders? The PageTitle, UserName, and ApplicationName properties will be repeated and become unwieldy to work with. Also, what if we want to define some page-level logic in the constructor of the class? We can no longer do that if we create an instance for every order that will be displayed.



                Composition over inheritance



                Here is a way we might re-factor the order presentation model such that it become a true view model and will be useful for displaying a single PresentationOrder object or a collection of PresentationOrder objects:



                public class PresentationOrderVM

                // Application properties
                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;

                // Business properties
                public PresentationOrder Order get; set;



                public class PresentationOrderVM

                // Application properties
                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;

                // Business properties
                public List<PresentationOrder> Orders get; set;



                Looking at the above two classes we can see that one way to think about a view model is that it is a presentation model that contains another presentation model as a property. The top level presentation model (i.e. view model) contains properties that are relevant to the page or application while presentation model (property) contains properties that are relevant to application data.



                We can take our design a step further and create a base view model class that can be used not only for PresentationOrders, but for any other class as well:



                public class BaseViewModel

                // Application properties
                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;



                Now we can simplify our PresentationOrderVM like this:



                public class PresentationOrderVM : BaseViewModel

                // Business properties
                public PresentationOrder Order get; set;


                public class PresentationOrderVM : BaseViewModel

                // Business properties
                public List<PresentationOrder> Orders get; set;



                We can make our BaseViewModel even more re-usable by making it generic:



                public class BaseViewModel<T>

                // Application properties
                public string PageTitle get; set;
                public string UserName get; set;
                public string ApplicationName get; set;

                // Business property
                public T BusinessObject get; set;



                Now our implementations are effortless:



                public class PresentationOrderVM : BaseViewModel<PresentationOrder>

                // done!


                public class PresentationOrderVM : BaseViewModel<List<PresentationOrder>>

                // done!







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Oct 7 '16 at 15:15

























                answered Mar 19 '15 at 1:30









                Sam

                2,59611737




                2,59611737







                • 1




                  Sam Thank You!! this helped me fully grasp the multi-faceted entity that is a: View-Model. I'm a college student just learning the MVC architecture, and this clarified a bunch of the capable functionalities that are exposed to the developer. If I could I would put a star next to your answer.
                  – Chef_Code
                  Jan 26 '16 at 3:13







                • 1




                  @Sam 'View models often contain the same properties as presentation models and DTO’s and for this reason they are often confused one for the other.' Does that mean they're commonly used instead of presentation models, or are they meant to contain the presentation models/dtos?
                  – Alexander Derck
                  Feb 1 '17 at 8:24






                • 2




                  @AlexanderDerck They are used for different purposes. They are confused one for the other (in error). No, you typically will not use a pres model in place of a view model. Much more common is that the VM "contains" the presentation model i.e. MyViewModel<MyPresModel>
                  – Sam
                  Feb 1 '17 at 15:05






                • 1




                  Way cool Sam! Thanks
                  – Stokely
                  Jul 13 '17 at 23:48






                • 1




                  @Sam Assuming model objects are live objects e.g. nhibernate models.. so by having BusinessObject aren't we exposing model/live objects directly to the view? i.e. the business object can be used to modify the database state directly? Also, what about nested view models? That would require multiple business object properties, right?
                  – Muhammad Ali
                  Sep 30 '17 at 9:54













                • 1




                  Sam Thank You!! this helped me fully grasp the multi-faceted entity that is a: View-Model. I'm a college student just learning the MVC architecture, and this clarified a bunch of the capable functionalities that are exposed to the developer. If I could I would put a star next to your answer.
                  – Chef_Code
                  Jan 26 '16 at 3:13







                • 1




                  @Sam 'View models often contain the same properties as presentation models and DTO’s and for this reason they are often confused one for the other.' Does that mean they're commonly used instead of presentation models, or are they meant to contain the presentation models/dtos?
                  – Alexander Derck
                  Feb 1 '17 at 8:24






                • 2




                  @AlexanderDerck They are used for different purposes. They are confused one for the other (in error). No, you typically will not use a pres model in place of a view model. Much more common is that the VM "contains" the presentation model i.e. MyViewModel<MyPresModel>
                  – Sam
                  Feb 1 '17 at 15:05






                • 1




                  Way cool Sam! Thanks
                  – Stokely
                  Jul 13 '17 at 23:48






                • 1




                  @Sam Assuming model objects are live objects e.g. nhibernate models.. so by having BusinessObject aren't we exposing model/live objects directly to the view? i.e. the business object can be used to modify the database state directly? Also, what about nested view models? That would require multiple business object properties, right?
                  – Muhammad Ali
                  Sep 30 '17 at 9:54








                1




                1




                Sam Thank You!! this helped me fully grasp the multi-faceted entity that is a: View-Model. I'm a college student just learning the MVC architecture, and this clarified a bunch of the capable functionalities that are exposed to the developer. If I could I would put a star next to your answer.
                – Chef_Code
                Jan 26 '16 at 3:13





                Sam Thank You!! this helped me fully grasp the multi-faceted entity that is a: View-Model. I'm a college student just learning the MVC architecture, and this clarified a bunch of the capable functionalities that are exposed to the developer. If I could I would put a star next to your answer.
                – Chef_Code
                Jan 26 '16 at 3:13





                1




                1




                @Sam 'View models often contain the same properties as presentation models and DTO’s and for this reason they are often confused one for the other.' Does that mean they're commonly used instead of presentation models, or are they meant to contain the presentation models/dtos?
                – Alexander Derck
                Feb 1 '17 at 8:24




                @Sam 'View models often contain the same properties as presentation models and DTO’s and for this reason they are often confused one for the other.' Does that mean they're commonly used instead of presentation models, or are they meant to contain the presentation models/dtos?
                – Alexander Derck
                Feb 1 '17 at 8:24




                2




                2




                @AlexanderDerck They are used for different purposes. They are confused one for the other (in error). No, you typically will not use a pres model in place of a view model. Much more common is that the VM "contains" the presentation model i.e. MyViewModel<MyPresModel>
                – Sam
                Feb 1 '17 at 15:05




                @AlexanderDerck They are used for different purposes. They are confused one for the other (in error). No, you typically will not use a pres model in place of a view model. Much more common is that the VM "contains" the presentation model i.e. MyViewModel<MyPresModel>
                – Sam
                Feb 1 '17 at 15:05




                1




                1




                Way cool Sam! Thanks
                – Stokely
                Jul 13 '17 at 23:48




                Way cool Sam! Thanks
                – Stokely
                Jul 13 '17 at 23:48




                1




                1




                @Sam Assuming model objects are live objects e.g. nhibernate models.. so by having BusinessObject aren't we exposing model/live objects directly to the view? i.e. the business object can be used to modify the database state directly? Also, what about nested view models? That would require multiple business object properties, right?
                – Muhammad Ali
                Sep 30 '17 at 9:54





                @Sam Assuming model objects are live objects e.g. nhibernate models.. so by having BusinessObject aren't we exposing model/live objects directly to the view? i.e. the business object can be used to modify the database state directly? Also, what about nested view models? That would require multiple business object properties, right?
                – Muhammad Ali
                Sep 30 '17 at 9:54












                22














                If you have properties specific to the view, and not related to the DB/Service/Data store, it is a good practice to use ViewModels. Say, you want to leave a checkbox selected based on a DB field (or two) but the DB field itself isn't a boolean. While it is possible to create these properties in the Model itself and keep it hidden from the binding to data, you may not want to clutter the Model depending on the amount of such fields and transactions.



                If there are too few view-specific data and/or transformations, you can use the Model itself






                share|improve this answer

























                  22














                  If you have properties specific to the view, and not related to the DB/Service/Data store, it is a good practice to use ViewModels. Say, you want to leave a checkbox selected based on a DB field (or two) but the DB field itself isn't a boolean. While it is possible to create these properties in the Model itself and keep it hidden from the binding to data, you may not want to clutter the Model depending on the amount of such fields and transactions.



                  If there are too few view-specific data and/or transformations, you can use the Model itself






                  share|improve this answer























                    22












                    22








                    22






                    If you have properties specific to the view, and not related to the DB/Service/Data store, it is a good practice to use ViewModels. Say, you want to leave a checkbox selected based on a DB field (or two) but the DB field itself isn't a boolean. While it is possible to create these properties in the Model itself and keep it hidden from the binding to data, you may not want to clutter the Model depending on the amount of such fields and transactions.



                    If there are too few view-specific data and/or transformations, you can use the Model itself






                    share|improve this answer












                    If you have properties specific to the view, and not related to the DB/Service/Data store, it is a good practice to use ViewModels. Say, you want to leave a checkbox selected based on a DB field (or two) but the DB field itself isn't a boolean. While it is possible to create these properties in the Model itself and keep it hidden from the binding to data, you may not want to clutter the Model depending on the amount of such fields and transactions.



                    If there are too few view-specific data and/or transformations, you can use the Model itself







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jun 16 '12 at 14:44









                    fozylet

                    1,04211123




                    1,04211123





















                        14














                        I didn't read all the posts but every answer seems to be missing one concept that really helped me "get it"...



                        If a Model is akin to a database Table, then a ViewModel is akin to a database View - A view typically either returns small amounts of data from one table, or, complex sets of data from multiple tables (joins).



                        I find myself using ViewModels to pass info into a view/form, and then transfering that data into a valid Model when the form posts back to the controller - also very handy for storing Lists(IEnumerable).






                        share|improve this answer

























                          14














                          I didn't read all the posts but every answer seems to be missing one concept that really helped me "get it"...



                          If a Model is akin to a database Table, then a ViewModel is akin to a database View - A view typically either returns small amounts of data from one table, or, complex sets of data from multiple tables (joins).



                          I find myself using ViewModels to pass info into a view/form, and then transfering that data into a valid Model when the form posts back to the controller - also very handy for storing Lists(IEnumerable).






                          share|improve this answer























                            14












                            14








                            14






                            I didn't read all the posts but every answer seems to be missing one concept that really helped me "get it"...



                            If a Model is akin to a database Table, then a ViewModel is akin to a database View - A view typically either returns small amounts of data from one table, or, complex sets of data from multiple tables (joins).



                            I find myself using ViewModels to pass info into a view/form, and then transfering that data into a valid Model when the form posts back to the controller - also very handy for storing Lists(IEnumerable).






                            share|improve this answer












                            I didn't read all the posts but every answer seems to be missing one concept that really helped me "get it"...



                            If a Model is akin to a database Table, then a ViewModel is akin to a database View - A view typically either returns small amounts of data from one table, or, complex sets of data from multiple tables (joins).



                            I find myself using ViewModels to pass info into a view/form, and then transfering that data into a valid Model when the form posts back to the controller - also very handy for storing Lists(IEnumerable).







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Sep 9 '16 at 20:53









                            halfacreSal

                            18018




                            18018





















                                10














                                MVC doesn't have a viewmodel: it has a model, view and controller. A viewmodel is part of MVVM (Model-View-Viewmodel). MVVM is derived from the Presentation Model and is popularized in WPF. There should also be a model in MVVM, but most people miss the point of that pattern completely and they will only have a view and a viewmodel. The model in MVC is similar to the model in MVVM.



                                In MVC the process is split into 3 different responsibilities:



                                • View is responsible for presenting the data to the user

                                • A controller is responsible for the page flow

                                • A model is responsible for the business logic

                                MVC is not very suitable for web applications. It is a pattern introduced by Smalltalk for creating desktop applications. A web environment behaves completely different. It doesn't make much sense to copy a 40-year old concept from the desktop development and paste it into a web enviroment. However a lot of people think this is ok, because their application compiles and returns the correct values. That is, in my opinion, not enough to declare a certain design choice as ok.



                                An example of a model in a web application could be:



                                public class LoginModel

                                private readonly AuthenticationService authentication;

                                public LoginModel(AuthenticationService authentication)

                                this.authentication = authentication;


                                public bool Login()

                                return authentication.Login(Username, Password);


                                public string Username get; set;
                                public string Password get; set;



                                The controller can use it like this:



                                public class LoginController

                                [HttpPost]
                                public ActionResult Login(LoginModel model)

                                bool success = model.Login();

                                if (success)

                                return new RedirectResult("/dashboard");

                                else

                                TempData["message"] = "Invalid username and/or password";
                                return new RedirectResult("/login");





                                Your controller methods and your models will be small, easily testable and to the point.






                                share|improve this answer






















                                • Thank you for the insight into MVVM architecture, but why is MVC not OK? Your reasoning is questionable and suspect to favoritism. Granted I know nothing about MVVM, but if an architecture such as MVC can mimic the behavior with-out having to write 50k lines of code, then whats the big deal?
                                  – Chef_Code
                                  Jan 26 '16 at 3:23











                                • @Chef_Code: It is not questionable or favoritism: just read the original paper about MVC. Going back to the source is much better than blindly following the herd without question (aka "best practices"). MVC is meant for much smaller units: e.g. a button on a screen is composed of a model, view and controller. In Web-MVC the entire page has a controller, a model and a view. The model and view are supposed to be connected, so that changes in the model are immediately reflected in the view and vice versa. Mimicking is a very big deal. An architecture shouldn't lie to it's developers.
                                  – Jeroen
                                  Jan 26 '16 at 11:49






                                • 1




                                  @jeroen The acronym MVC has been stolen and mangled. Yes MVC does not have a VM but it also doesn't have a Repository or a service layer and those objects are widely used in web sites. I believe the OP is asking "how do I introduce and use a VM in MVC". In the new meaning of MVC a model is not where business logic belongs. Business logic belongs in a service layer for a web or a desktop app using MVC or MVVM. The term model describes the business objects that are passed to/from the service layer. These definitions are vastly different from the original description of MVC.
                                  – Sam
                                  Feb 15 '16 at 16:46







                                • 1




                                  @Sam Not everything that is part of a website, can be called part of MVC. There is no new meaning of MVC. There is the correct meaning and the "something completely unrelated that people confuse with MVC"-meaning. Saying that the model is responsible for the business logic, is not the same as business logic is coded in the model. Most of the time the model acts as a facade to the application.
                                  – Jeroen
                                  Feb 23 '16 at 13:48










                                • The main flaw I see in Microsoft's MVC is the locking of a Model with a View. That itself defeats the whole purpose of all this separation that's been going on in N-Tier designs the past 20 years. They wasted our time forcing us to use "WebForms" in 2002 which was another Desktop-inspired model hoisted onto the Web World. Now they've tossded that out but hoisted yet again another desktop model on this new paradigm for web dev. In the mean time Google and others are building giant client-side models that separate it all. Im thinking old ASP VBScript from 1998 was their truest web dev system.
                                  – Stokely
                                  Jul 13 '17 at 23:58
















                                10














                                MVC doesn't have a viewmodel: it has a model, view and controller. A viewmodel is part of MVVM (Model-View-Viewmodel). MVVM is derived from the Presentation Model and is popularized in WPF. There should also be a model in MVVM, but most people miss the point of that pattern completely and they will only have a view and a viewmodel. The model in MVC is similar to the model in MVVM.



                                In MVC the process is split into 3 different responsibilities:



                                • View is responsible for presenting the data to the user

                                • A controller is responsible for the page flow

                                • A model is responsible for the business logic

                                MVC is not very suitable for web applications. It is a pattern introduced by Smalltalk for creating desktop applications. A web environment behaves completely different. It doesn't make much sense to copy a 40-year old concept from the desktop development and paste it into a web enviroment. However a lot of people think this is ok, because their application compiles and returns the correct values. That is, in my opinion, not enough to declare a certain design choice as ok.



                                An example of a model in a web application could be:



                                public class LoginModel

                                private readonly AuthenticationService authentication;

                                public LoginModel(AuthenticationService authentication)

                                this.authentication = authentication;


                                public bool Login()

                                return authentication.Login(Username, Password);


                                public string Username get; set;
                                public string Password get; set;



                                The controller can use it like this:



                                public class LoginController

                                [HttpPost]
                                public ActionResult Login(LoginModel model)

                                bool success = model.Login();

                                if (success)

                                return new RedirectResult("/dashboard");

                                else

                                TempData["message"] = "Invalid username and/or password";
                                return new RedirectResult("/login");





                                Your controller methods and your models will be small, easily testable and to the point.






                                share|improve this answer






















                                • Thank you for the insight into MVVM architecture, but why is MVC not OK? Your reasoning is questionable and suspect to favoritism. Granted I know nothing about MVVM, but if an architecture such as MVC can mimic the behavior with-out having to write 50k lines of code, then whats the big deal?
                                  – Chef_Code
                                  Jan 26 '16 at 3:23











                                • @Chef_Code: It is not questionable or favoritism: just read the original paper about MVC. Going back to the source is much better than blindly following the herd without question (aka "best practices"). MVC is meant for much smaller units: e.g. a button on a screen is composed of a model, view and controller. In Web-MVC the entire page has a controller, a model and a view. The model and view are supposed to be connected, so that changes in the model are immediately reflected in the view and vice versa. Mimicking is a very big deal. An architecture shouldn't lie to it's developers.
                                  – Jeroen
                                  Jan 26 '16 at 11:49






                                • 1




                                  @jeroen The acronym MVC has been stolen and mangled. Yes MVC does not have a VM but it also doesn't have a Repository or a service layer and those objects are widely used in web sites. I believe the OP is asking "how do I introduce and use a VM in MVC". In the new meaning of MVC a model is not where business logic belongs. Business logic belongs in a service layer for a web or a desktop app using MVC or MVVM. The term model describes the business objects that are passed to/from the service layer. These definitions are vastly different from the original description of MVC.
                                  – Sam
                                  Feb 15 '16 at 16:46







                                • 1




                                  @Sam Not everything that is part of a website, can be called part of MVC. There is no new meaning of MVC. There is the correct meaning and the "something completely unrelated that people confuse with MVC"-meaning. Saying that the model is responsible for the business logic, is not the same as business logic is coded in the model. Most of the time the model acts as a facade to the application.
                                  – Jeroen
                                  Feb 23 '16 at 13:48










                                • The main flaw I see in Microsoft's MVC is the locking of a Model with a View. That itself defeats the whole purpose of all this separation that's been going on in N-Tier designs the past 20 years. They wasted our time forcing us to use "WebForms" in 2002 which was another Desktop-inspired model hoisted onto the Web World. Now they've tossded that out but hoisted yet again another desktop model on this new paradigm for web dev. In the mean time Google and others are building giant client-side models that separate it all. Im thinking old ASP VBScript from 1998 was their truest web dev system.
                                  – Stokely
                                  Jul 13 '17 at 23:58














                                10












                                10








                                10






                                MVC doesn't have a viewmodel: it has a model, view and controller. A viewmodel is part of MVVM (Model-View-Viewmodel). MVVM is derived from the Presentation Model and is popularized in WPF. There should also be a model in MVVM, but most people miss the point of that pattern completely and they will only have a view and a viewmodel. The model in MVC is similar to the model in MVVM.



                                In MVC the process is split into 3 different responsibilities:



                                • View is responsible for presenting the data to the user

                                • A controller is responsible for the page flow

                                • A model is responsible for the business logic

                                MVC is not very suitable for web applications. It is a pattern introduced by Smalltalk for creating desktop applications. A web environment behaves completely different. It doesn't make much sense to copy a 40-year old concept from the desktop development and paste it into a web enviroment. However a lot of people think this is ok, because their application compiles and returns the correct values. That is, in my opinion, not enough to declare a certain design choice as ok.



                                An example of a model in a web application could be:



                                public class LoginModel

                                private readonly AuthenticationService authentication;

                                public LoginModel(AuthenticationService authentication)

                                this.authentication = authentication;


                                public bool Login()

                                return authentication.Login(Username, Password);


                                public string Username get; set;
                                public string Password get; set;



                                The controller can use it like this:



                                public class LoginController

                                [HttpPost]
                                public ActionResult Login(LoginModel model)

                                bool success = model.Login();

                                if (success)

                                return new RedirectResult("/dashboard");

                                else

                                TempData["message"] = "Invalid username and/or password";
                                return new RedirectResult("/login");





                                Your controller methods and your models will be small, easily testable and to the point.






                                share|improve this answer














                                MVC doesn't have a viewmodel: it has a model, view and controller. A viewmodel is part of MVVM (Model-View-Viewmodel). MVVM is derived from the Presentation Model and is popularized in WPF. There should also be a model in MVVM, but most people miss the point of that pattern completely and they will only have a view and a viewmodel. The model in MVC is similar to the model in MVVM.



                                In MVC the process is split into 3 different responsibilities:



                                • View is responsible for presenting the data to the user

                                • A controller is responsible for the page flow

                                • A model is responsible for the business logic

                                MVC is not very suitable for web applications. It is a pattern introduced by Smalltalk for creating desktop applications. A web environment behaves completely different. It doesn't make much sense to copy a 40-year old concept from the desktop development and paste it into a web enviroment. However a lot of people think this is ok, because their application compiles and returns the correct values. That is, in my opinion, not enough to declare a certain design choice as ok.



                                An example of a model in a web application could be:



                                public class LoginModel

                                private readonly AuthenticationService authentication;

                                public LoginModel(AuthenticationService authentication)

                                this.authentication = authentication;


                                public bool Login()

                                return authentication.Login(Username, Password);


                                public string Username get; set;
                                public string Password get; set;



                                The controller can use it like this:



                                public class LoginController

                                [HttpPost]
                                public ActionResult Login(LoginModel model)

                                bool success = model.Login();

                                if (success)

                                return new RedirectResult("/dashboard");

                                else

                                TempData["message"] = "Invalid username and/or password";
                                return new RedirectResult("/login");





                                Your controller methods and your models will be small, easily testable and to the point.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Dec 3 '15 at 16:10

























                                answered Dec 3 '15 at 16:04









                                Jeroen

                                693419




                                693419











                                • Thank you for the insight into MVVM architecture, but why is MVC not OK? Your reasoning is questionable and suspect to favoritism. Granted I know nothing about MVVM, but if an architecture such as MVC can mimic the behavior with-out having to write 50k lines of code, then whats the big deal?
                                  – Chef_Code
                                  Jan 26 '16 at 3:23











                                • @Chef_Code: It is not questionable or favoritism: just read the original paper about MVC. Going back to the source is much better than blindly following the herd without question (aka "best practices"). MVC is meant for much smaller units: e.g. a button on a screen is composed of a model, view and controller. In Web-MVC the entire page has a controller, a model and a view. The model and view are supposed to be connected, so that changes in the model are immediately reflected in the view and vice versa. Mimicking is a very big deal. An architecture shouldn't lie to it's developers.
                                  – Jeroen
                                  Jan 26 '16 at 11:49






                                • 1




                                  @jeroen The acronym MVC has been stolen and mangled. Yes MVC does not have a VM but it also doesn't have a Repository or a service layer and those objects are widely used in web sites. I believe the OP is asking "how do I introduce and use a VM in MVC". In the new meaning of MVC a model is not where business logic belongs. Business logic belongs in a service layer for a web or a desktop app using MVC or MVVM. The term model describes the business objects that are passed to/from the service layer. These definitions are vastly different from the original description of MVC.
                                  – Sam
                                  Feb 15 '16 at 16:46







                                • 1




                                  @Sam Not everything that is part of a website, can be called part of MVC. There is no new meaning of MVC. There is the correct meaning and the "something completely unrelated that people confuse with MVC"-meaning. Saying that the model is responsible for the business logic, is not the same as business logic is coded in the model. Most of the time the model acts as a facade to the application.
                                  – Jeroen
                                  Feb 23 '16 at 13:48










                                • The main flaw I see in Microsoft's MVC is the locking of a Model with a View. That itself defeats the whole purpose of all this separation that's been going on in N-Tier designs the past 20 years. They wasted our time forcing us to use "WebForms" in 2002 which was another Desktop-inspired model hoisted onto the Web World. Now they've tossded that out but hoisted yet again another desktop model on this new paradigm for web dev. In the mean time Google and others are building giant client-side models that separate it all. Im thinking old ASP VBScript from 1998 was their truest web dev system.
                                  – Stokely
                                  Jul 13 '17 at 23:58

















                                • Thank you for the insight into MVVM architecture, but why is MVC not OK? Your reasoning is questionable and suspect to favoritism. Granted I know nothing about MVVM, but if an architecture such as MVC can mimic the behavior with-out having to write 50k lines of code, then whats the big deal?
                                  – Chef_Code
                                  Jan 26 '16 at 3:23











                                • @Chef_Code: It is not questionable or favoritism: just read the original paper about MVC. Going back to the source is much better than blindly following the herd without question (aka "best practices"). MVC is meant for much smaller units: e.g. a button on a screen is composed of a model, view and controller. In Web-MVC the entire page has a controller, a model and a view. The model and view are supposed to be connected, so that changes in the model are immediately reflected in the view and vice versa. Mimicking is a very big deal. An architecture shouldn't lie to it's developers.
                                  – Jeroen
                                  Jan 26 '16 at 11:49






                                • 1




                                  @jeroen The acronym MVC has been stolen and mangled. Yes MVC does not have a VM but it also doesn't have a Repository or a service layer and those objects are widely used in web sites. I believe the OP is asking "how do I introduce and use a VM in MVC". In the new meaning of MVC a model is not where business logic belongs. Business logic belongs in a service layer for a web or a desktop app using MVC or MVVM. The term model describes the business objects that are passed to/from the service layer. These definitions are vastly different from the original description of MVC.
                                  – Sam
                                  Feb 15 '16 at 16:46







                                • 1




                                  @Sam Not everything that is part of a website, can be called part of MVC. There is no new meaning of MVC. There is the correct meaning and the "something completely unrelated that people confuse with MVC"-meaning. Saying that the model is responsible for the business logic, is not the same as business logic is coded in the model. Most of the time the model acts as a facade to the application.
                                  – Jeroen
                                  Feb 23 '16 at 13:48










                                • The main flaw I see in Microsoft's MVC is the locking of a Model with a View. That itself defeats the whole purpose of all this separation that's been going on in N-Tier designs the past 20 years. They wasted our time forcing us to use "WebForms" in 2002 which was another Desktop-inspired model hoisted onto the Web World. Now they've tossded that out but hoisted yet again another desktop model on this new paradigm for web dev. In the mean time Google and others are building giant client-side models that separate it all. Im thinking old ASP VBScript from 1998 was their truest web dev system.
                                  – Stokely
                                  Jul 13 '17 at 23:58
















                                Thank you for the insight into MVVM architecture, but why is MVC not OK? Your reasoning is questionable and suspect to favoritism. Granted I know nothing about MVVM, but if an architecture such as MVC can mimic the behavior with-out having to write 50k lines of code, then whats the big deal?
                                – Chef_Code
                                Jan 26 '16 at 3:23





                                Thank you for the insight into MVVM architecture, but why is MVC not OK? Your reasoning is questionable and suspect to favoritism. Granted I know nothing about MVVM, but if an architecture such as MVC can mimic the behavior with-out having to write 50k lines of code, then whats the big deal?
                                – Chef_Code
                                Jan 26 '16 at 3:23













                                @Chef_Code: It is not questionable or favoritism: just read the original paper about MVC. Going back to the source is much better than blindly following the herd without question (aka "best practices"). MVC is meant for much smaller units: e.g. a button on a screen is composed of a model, view and controller. In Web-MVC the entire page has a controller, a model and a view. The model and view are supposed to be connected, so that changes in the model are immediately reflected in the view and vice versa. Mimicking is a very big deal. An architecture shouldn't lie to it's developers.
                                – Jeroen
                                Jan 26 '16 at 11:49




                                @Chef_Code: It is not questionable or favoritism: just read the original paper about MVC. Going back to the source is much better than blindly following the herd without question (aka "best practices"). MVC is meant for much smaller units: e.g. a button on a screen is composed of a model, view and controller. In Web-MVC the entire page has a controller, a model and a view. The model and view are supposed to be connected, so that changes in the model are immediately reflected in the view and vice versa. Mimicking is a very big deal. An architecture shouldn't lie to it's developers.
                                – Jeroen
                                Jan 26 '16 at 11:49




                                1




                                1




                                @jeroen The acronym MVC has been stolen and mangled. Yes MVC does not have a VM but it also doesn't have a Repository or a service layer and those objects are widely used in web sites. I believe the OP is asking "how do I introduce and use a VM in MVC". In the new meaning of MVC a model is not where business logic belongs. Business logic belongs in a service layer for a web or a desktop app using MVC or MVVM. The term model describes the business objects that are passed to/from the service layer. These definitions are vastly different from the original description of MVC.
                                – Sam
                                Feb 15 '16 at 16:46





                                @jeroen The acronym MVC has been stolen and mangled. Yes MVC does not have a VM but it also doesn't have a Repository or a service layer and those objects are widely used in web sites. I believe the OP is asking "how do I introduce and use a VM in MVC". In the new meaning of MVC a model is not where business logic belongs. Business logic belongs in a service layer for a web or a desktop app using MVC or MVVM. The term model describes the business objects that are passed to/from the service layer. These definitions are vastly different from the original description of MVC.
                                – Sam
                                Feb 15 '16 at 16:46





                                1




                                1




                                @Sam Not everything that is part of a website, can be called part of MVC. There is no new meaning of MVC. There is the correct meaning and the "something completely unrelated that people confuse with MVC"-meaning. Saying that the model is responsible for the business logic, is not the same as business logic is coded in the model. Most of the time the model acts as a facade to the application.
                                – Jeroen
                                Feb 23 '16 at 13:48




                                @Sam Not everything that is part of a website, can be called part of MVC. There is no new meaning of MVC. There is the correct meaning and the "something completely unrelated that people confuse with MVC"-meaning. Saying that the model is responsible for the business logic, is not the same as business logic is coded in the model. Most of the time the model acts as a facade to the application.
                                – Jeroen
                                Feb 23 '16 at 13:48












                                The main flaw I see in Microsoft's MVC is the locking of a Model with a View. That itself defeats the whole purpose of all this separation that's been going on in N-Tier designs the past 20 years. They wasted our time forcing us to use "WebForms" in 2002 which was another Desktop-inspired model hoisted onto the Web World. Now they've tossded that out but hoisted yet again another desktop model on this new paradigm for web dev. In the mean time Google and others are building giant client-side models that separate it all. Im thinking old ASP VBScript from 1998 was their truest web dev system.
                                – Stokely
                                Jul 13 '17 at 23:58





                                The main flaw I see in Microsoft's MVC is the locking of a Model with a View. That itself defeats the whole purpose of all this separation that's been going on in N-Tier designs the past 20 years. They wasted our time forcing us to use "WebForms" in 2002 which was another Desktop-inspired model hoisted onto the Web World. Now they've tossded that out but hoisted yet again another desktop model on this new paradigm for web dev. In the mean time Google and others are building giant client-side models that separate it all. Im thinking old ASP VBScript from 1998 was their truest web dev system.
                                – Stokely
                                Jul 13 '17 at 23:58












                                10














                                A lot of big examples, let me explain in clear and crispy way.



                                ViewModel = Model that is created to serve the view.



                                ASP.NET MVC view can't have more than one model so if we need to display properties from more than one models into the view, it is not possible. ViewModel serves this purpose.



                                View Model is a model class that can hold only those properties that is required for a view. It can also contains properties from more than one entities (tables) of the database. As the name suggests, this model is created specific to the View requirements.



                                Few examples of View Models are below



                                • To list data from more than entities in a view page – we can create a
                                  View model and have properties of all the entities for which we want
                                  to list data. Join those database entities and set View model
                                  properties and return to the View to show data of different
                                  entities in one tabular form

                                • View model may define only specific fields of a single entity that is
                                  required for the View.

                                ViewModel can also be used to insert, update records into more than one entities however the main use of ViewModel is to display columns from multiple entities (model) into a single view.



                                The way of creating ViewModel is same as creating Model, the way of creating view for the Viewmodel is same as creating view for Model.



                                Here is a small example of List data using ViewModel.



                                Hope this will be useful.






                                share|improve this answer

























                                  10














                                  A lot of big examples, let me explain in clear and crispy way.



                                  ViewModel = Model that is created to serve the view.



                                  ASP.NET MVC view can't have more than one model so if we need to display properties from more than one models into the view, it is not possible. ViewModel serves this purpose.



                                  View Model is a model class that can hold only those properties that is required for a view. It can also contains properties from more than one entities (tables) of the database. As the name suggests, this model is created specific to the View requirements.



                                  Few examples of View Models are below



                                  • To list data from more than entities in a view page – we can create a
                                    View model and have properties of all the entities for which we want
                                    to list data. Join those database entities and set View model
                                    properties and return to the View to show data of different
                                    entities in one tabular form

                                  • View model may define only specific fields of a single entity that is
                                    required for the View.

                                  ViewModel can also be used to insert, update records into more than one entities however the main use of ViewModel is to display columns from multiple entities (model) into a single view.



                                  The way of creating ViewModel is same as creating Model, the way of creating view for the Viewmodel is same as creating view for Model.



                                  Here is a small example of List data using ViewModel.



                                  Hope this will be useful.






                                  share|improve this answer























                                    10












                                    10








                                    10






                                    A lot of big examples, let me explain in clear and crispy way.



                                    ViewModel = Model that is created to serve the view.



                                    ASP.NET MVC view can't have more than one model so if we need to display properties from more than one models into the view, it is not possible. ViewModel serves this purpose.



                                    View Model is a model class that can hold only those properties that is required for a view. It can also contains properties from more than one entities (tables) of the database. As the name suggests, this model is created specific to the View requirements.



                                    Few examples of View Models are below



                                    • To list data from more than entities in a view page – we can create a
                                      View model and have properties of all the entities for which we want
                                      to list data. Join those database entities and set View model
                                      properties and return to the View to show data of different
                                      entities in one tabular form

                                    • View model may define only specific fields of a single entity that is
                                      required for the View.

                                    ViewModel can also be used to insert, update records into more than one entities however the main use of ViewModel is to display columns from multiple entities (model) into a single view.



                                    The way of creating ViewModel is same as creating Model, the way of creating view for the Viewmodel is same as creating view for Model.



                                    Here is a small example of List data using ViewModel.



                                    Hope this will be useful.






                                    share|improve this answer












                                    A lot of big examples, let me explain in clear and crispy way.



                                    ViewModel = Model that is created to serve the view.



                                    ASP.NET MVC view can't have more than one model so if we need to display properties from more than one models into the view, it is not possible. ViewModel serves this purpose.



                                    View Model is a model class that can hold only those properties that is required for a view. It can also contains properties from more than one entities (tables) of the database. As the name suggests, this model is created specific to the View requirements.



                                    Few examples of View Models are below



                                    • To list data from more than entities in a view page – we can create a
                                      View model and have properties of all the entities for which we want
                                      to list data. Join those database entities and set View model
                                      properties and return to the View to show data of different
                                      entities in one tabular form

                                    • View model may define only specific fields of a single entity that is
                                      required for the View.

                                    ViewModel can also be used to insert, update records into more than one entities however the main use of ViewModel is to display columns from multiple entities (model) into a single view.



                                    The way of creating ViewModel is same as creating Model, the way of creating view for the Viewmodel is same as creating view for Model.



                                    Here is a small example of List data using ViewModel.



                                    Hope this will be useful.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Jan 29 '16 at 7:46









                                    Sheo Narayan

                                    1,05121115




                                    1,05121115





















                                        10














                                        View model a is simple class which can contain more than one class property. We use it to inherit all the required properties, e.g. I have two classes Student and Subject



                                        Public class Student

                                        public int Id get; set;
                                        public string Name get; set;

                                        Public class Subject

                                        public int SubjectID get; set;
                                        public string SubjectName get; set;



                                        Now we want to display records student's Name and Subject's Name in View (In MVC), but it's not possible to add more than one classes like:



                                         @model ProjectName.Model.Student 
                                        @model ProjectName.Model.Subject


                                        the code above will throw an error...



                                        Now we create one class and can give it any name, but this format "XyzViewModel" will make it easier to understand. It is inheritance concept.
                                        Now we create a third class with the following name:



                                        public class StudentViewModel:Subject

                                        public int ID get; set;
                                        public string Name get; set;



                                        Now we use this ViewModel in View




                                        @model ProjectName.Model.StudentViewModel




                                        Now we are able to access all the properties of StudentViewModel and inherited class in View.






                                        share|improve this answer



























                                          10














                                          View model a is simple class which can contain more than one class property. We use it to inherit all the required properties, e.g. I have two classes Student and Subject



                                          Public class Student

                                          public int Id get; set;
                                          public string Name get; set;

                                          Public class Subject

                                          public int SubjectID get; set;
                                          public string SubjectName get; set;



                                          Now we want to display records student's Name and Subject's Name in View (In MVC), but it's not possible to add more than one classes like:



                                           @model ProjectName.Model.Student 
                                          @model ProjectName.Model.Subject


                                          the code above will throw an error...



                                          Now we create one class and can give it any name, but this format "XyzViewModel" will make it easier to understand. It is inheritance concept.
                                          Now we create a third class with the following name:



                                          public class StudentViewModel:Subject

                                          public int ID get; set;
                                          public string Name get; set;



                                          Now we use this ViewModel in View




                                          @model ProjectName.Model.StudentViewModel




                                          Now we are able to access all the properties of StudentViewModel and inherited class in View.






                                          share|improve this answer

























                                            10












                                            10








                                            10






                                            View model a is simple class which can contain more than one class property. We use it to inherit all the required properties, e.g. I have two classes Student and Subject



                                            Public class Student

                                            public int Id get; set;
                                            public string Name get; set;

                                            Public class Subject

                                            public int SubjectID get; set;
                                            public string SubjectName get; set;



                                            Now we want to display records student's Name and Subject's Name in View (In MVC), but it's not possible to add more than one classes like:



                                             @model ProjectName.Model.Student 
                                            @model ProjectName.Model.Subject


                                            the code above will throw an error...



                                            Now we create one class and can give it any name, but this format "XyzViewModel" will make it easier to understand. It is inheritance concept.
                                            Now we create a third class with the following name:



                                            public class StudentViewModel:Subject

                                            public int ID get; set;
                                            public string Name get; set;



                                            Now we use this ViewModel in View




                                            @model ProjectName.Model.StudentViewModel




                                            Now we are able to access all the properties of StudentViewModel and inherited class in View.






                                            share|improve this answer














                                            View model a is simple class which can contain more than one class property. We use it to inherit all the required properties, e.g. I have two classes Student and Subject



                                            Public class Student

                                            public int Id get; set;
                                            public string Name get; set;

                                            Public class Subject

                                            public int SubjectID get; set;
                                            public string SubjectName get; set;



                                            Now we want to display records student's Name and Subject's Name in View (In MVC), but it's not possible to add more than one classes like:



                                             @model ProjectName.Model.Student 
                                            @model ProjectName.Model.Subject


                                            the code above will throw an error...



                                            Now we create one class and can give it any name, but this format "XyzViewModel" will make it easier to understand. It is inheritance concept.
                                            Now we create a third class with the following name:



                                            public class StudentViewModel:Subject

                                            public int ID get; set;
                                            public string Name get; set;



                                            Now we use this ViewModel in View




                                            @model ProjectName.Model.StudentViewModel




                                            Now we are able to access all the properties of StudentViewModel and inherited class in View.







                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited May 31 '16 at 11:49









                                            demonicdaron

                                            387317




                                            387317










                                            answered Sep 19 '15 at 6:30









                                            Mayank

                                            12114




                                            12114





















                                                4














                                                ViewModel is workarround that patches the conceptual clumsiness of the MVC framework. It represents the 4th layer in the 3-layer Model-View-Controller architecture. when Model (domain model) is not appropriate, too big (bigger than 2-3 fields) for the View, we create smaller ViewModel to pass it to the View.






                                                share|improve this answer

























                                                  4














                                                  ViewModel is workarround that patches the conceptual clumsiness of the MVC framework. It represents the 4th layer in the 3-layer Model-View-Controller architecture. when Model (domain model) is not appropriate, too big (bigger than 2-3 fields) for the View, we create smaller ViewModel to pass it to the View.






                                                  share|improve this answer























                                                    4












                                                    4








                                                    4






                                                    ViewModel is workarround that patches the conceptual clumsiness of the MVC framework. It represents the 4th layer in the 3-layer Model-View-Controller architecture. when Model (domain model) is not appropriate, too big (bigger than 2-3 fields) for the View, we create smaller ViewModel to pass it to the View.






                                                    share|improve this answer












                                                    ViewModel is workarround that patches the conceptual clumsiness of the MVC framework. It represents the 4th layer in the 3-layer Model-View-Controller architecture. when Model (domain model) is not appropriate, too big (bigger than 2-3 fields) for the View, we create smaller ViewModel to pass it to the View.







                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered Oct 3 '17 at 9:03









                                                    gsivanov

                                                    633




                                                    633





















                                                        1














                                                        A view model is a conceptual model of data. Its use is to for example either get a subset or combine data from different tables.



                                                        You might only want specific properties, so this allows you to only load those and not additional unneccesary properties






                                                        share|improve this answer

























                                                          1














                                                          A view model is a conceptual model of data. Its use is to for example either get a subset or combine data from different tables.



                                                          You might only want specific properties, so this allows you to only load those and not additional unneccesary properties






                                                          share|improve this answer























                                                            1












                                                            1








                                                            1






                                                            A view model is a conceptual model of data. Its use is to for example either get a subset or combine data from different tables.



                                                            You might only want specific properties, so this allows you to only load those and not additional unneccesary properties






                                                            share|improve this answer












                                                            A view model is a conceptual model of data. Its use is to for example either get a subset or combine data from different tables.



                                                            You might only want specific properties, so this allows you to only load those and not additional unneccesary properties







                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Sep 21 '18 at 9:16









                                                            Stephen Mooney

                                                            12218




                                                            12218





















                                                                1














                                                                • ViewModel contain fields that are represented in the view (for
                                                                  LabelFor,EditorFor,DisplayFor helpers)

                                                                • ViewModel can have specific validation rules using data annotations
                                                                  or IDataErrorInfo.

                                                                • ViewModel can have multiple entities or objects from different data
                                                                  models or data source.

                                                                Designing ViewModel



                                                                public class UserLoginViewModel 

                                                                [Required(ErrorMessage = "Please enter your username")]
                                                                [Display(Name = "User Name")]
                                                                [MaxLength(50)]
                                                                public string UserName get; set;
                                                                [Required(ErrorMessage = "Please enter your password")]
                                                                [Display(Name = "Password")]
                                                                [MaxLength(50)]
                                                                public string Password get; set;



                                                                Presenting the viewmodel in the view



                                                                @model MyModels.UserLoginViewModel 
                                                                @
                                                                ViewBag.Title = "User Login";
                                                                Layout = "~/Views/Shared/_Layout.cshtml";

                                                                @using (Html.BeginForm())

                                                                <div class="editor-label">
                                                                @Html.LabelFor(m => m.UserName)
                                                                </div>
                                                                <div class="editor-field">
                                                                @Html.TextBoxFor(m => m.UserName)
                                                                @Html.ValidationMessageFor(m => m.UserName)
                                                                </div>
                                                                <div class="editor-label">
                                                                @Html.LabelFor(m => m.Password)
                                                                </div>
                                                                <div class="editor-field">
                                                                @Html.PasswordFor(m => m.Password)
                                                                @Html.ValidationMessageFor(m => m.Password)
                                                                </div>
                                                                <p>
                                                                <input type="submit" value="Log In" />
                                                                </p>
                                                                </div>



                                                                Working with Action



                                                                public ActionResult Login()

                                                                return View();

                                                                [HttpPost]
                                                                public ActionResult Login(UserLoginViewModel user)

                                                                // To acces data using LINQ
                                                                DataClassesDataContext mobjentity = new DataClassesDataContext();
                                                                if (ModelState.IsValid)

                                                                try

                                                                var q = mobjentity.tblUsers.Where(m => m.UserName == user.UserName && m.Password == user.Password).ToList();
                                                                if (q.Count > 0)

                                                                return RedirectToAction("MyAccount");

                                                                else

                                                                ModelState.AddModelError("", "The user name or password provided is incorrect.");


                                                                catch (Exception ex)



                                                                return View(user);



                                                                1. In ViewModel put only those fields/data that you want to display on
                                                                  the view/page.

                                                                2. Since view reperesents the properties of the ViewModel, hence it is
                                                                  easy for rendering and maintenance.

                                                                3. Use a mapper when ViewModel become more complex.





                                                                share|improve this answer

























                                                                  1














                                                                  • ViewModel contain fields that are represented in the view (for
                                                                    LabelFor,EditorFor,DisplayFor helpers)

                                                                  • ViewModel can have specific validation rules using data annotations
                                                                    or IDataErrorInfo.

                                                                  • ViewModel can have multiple entities or objects from different data
                                                                    models or data source.

                                                                  Designing ViewModel



                                                                  public class UserLoginViewModel 

                                                                  [Required(ErrorMessage = "Please enter your username")]
                                                                  [Display(Name = "User Name")]
                                                                  [MaxLength(50)]
                                                                  public string UserName get; set;
                                                                  [Required(ErrorMessage = "Please enter your password")]
                                                                  [Display(Name = "Password")]
                                                                  [MaxLength(50)]
                                                                  public string Password get; set;



                                                                  Presenting the viewmodel in the view



                                                                  @model MyModels.UserLoginViewModel 
                                                                  @
                                                                  ViewBag.Title = "User Login";
                                                                  Layout = "~/Views/Shared/_Layout.cshtml";

                                                                  @using (Html.BeginForm())

                                                                  <div class="editor-label">
                                                                  @Html.LabelFor(m => m.UserName)
                                                                  </div>
                                                                  <div class="editor-field">
                                                                  @Html.TextBoxFor(m => m.UserName)
                                                                  @Html.ValidationMessageFor(m => m.UserName)
                                                                  </div>
                                                                  <div class="editor-label">
                                                                  @Html.LabelFor(m => m.Password)
                                                                  </div>
                                                                  <div class="editor-field">
                                                                  @Html.PasswordFor(m => m.Password)
                                                                  @Html.ValidationMessageFor(m => m.Password)
                                                                  </div>
                                                                  <p>
                                                                  <input type="submit" value="Log In" />
                                                                  </p>
                                                                  </div>



                                                                  Working with Action



                                                                  public ActionResult Login()

                                                                  return View();

                                                                  [HttpPost]
                                                                  public ActionResult Login(UserLoginViewModel user)

                                                                  // To acces data using LINQ
                                                                  DataClassesDataContext mobjentity = new DataClassesDataContext();
                                                                  if (ModelState.IsValid)

                                                                  try

                                                                  var q = mobjentity.tblUsers.Where(m => m.UserName == user.UserName && m.Password == user.Password).ToList();
                                                                  if (q.Count > 0)

                                                                  return RedirectToAction("MyAccount");

                                                                  else

                                                                  ModelState.AddModelError("", "The user name or password provided is incorrect.");


                                                                  catch (Exception ex)



                                                                  return View(user);



                                                                  1. In ViewModel put only those fields/data that you want to display on
                                                                    the view/page.

                                                                  2. Since view reperesents the properties of the ViewModel, hence it is
                                                                    easy for rendering and maintenance.

                                                                  3. Use a mapper when ViewModel become more complex.





                                                                  share|improve this answer























                                                                    1












                                                                    1








                                                                    1






                                                                    • ViewModel contain fields that are represented in the view (for
                                                                      LabelFor,EditorFor,DisplayFor helpers)

                                                                    • ViewModel can have specific validation rules using data annotations
                                                                      or IDataErrorInfo.

                                                                    • ViewModel can have multiple entities or objects from different data
                                                                      models or data source.

                                                                    Designing ViewModel



                                                                    public class UserLoginViewModel 

                                                                    [Required(ErrorMessage = "Please enter your username")]
                                                                    [Display(Name = "User Name")]
                                                                    [MaxLength(50)]
                                                                    public string UserName get; set;
                                                                    [Required(ErrorMessage = "Please enter your password")]
                                                                    [Display(Name = "Password")]
                                                                    [MaxLength(50)]
                                                                    public string Password get; set;



                                                                    Presenting the viewmodel in the view



                                                                    @model MyModels.UserLoginViewModel 
                                                                    @
                                                                    ViewBag.Title = "User Login";
                                                                    Layout = "~/Views/Shared/_Layout.cshtml";

                                                                    @using (Html.BeginForm())

                                                                    <div class="editor-label">
                                                                    @Html.LabelFor(m => m.UserName)
                                                                    </div>
                                                                    <div class="editor-field">
                                                                    @Html.TextBoxFor(m => m.UserName)
                                                                    @Html.ValidationMessageFor(m => m.UserName)
                                                                    </div>
                                                                    <div class="editor-label">
                                                                    @Html.LabelFor(m => m.Password)
                                                                    </div>
                                                                    <div class="editor-field">
                                                                    @Html.PasswordFor(m => m.Password)
                                                                    @Html.ValidationMessageFor(m => m.Password)
                                                                    </div>
                                                                    <p>
                                                                    <input type="submit" value="Log In" />
                                                                    </p>
                                                                    </div>



                                                                    Working with Action



                                                                    public ActionResult Login()

                                                                    return View();

                                                                    [HttpPost]
                                                                    public ActionResult Login(UserLoginViewModel user)

                                                                    // To acces data using LINQ
                                                                    DataClassesDataContext mobjentity = new DataClassesDataContext();
                                                                    if (ModelState.IsValid)

                                                                    try

                                                                    var q = mobjentity.tblUsers.Where(m => m.UserName == user.UserName && m.Password == user.Password).ToList();
                                                                    if (q.Count > 0)

                                                                    return RedirectToAction("MyAccount");

                                                                    else

                                                                    ModelState.AddModelError("", "The user name or password provided is incorrect.");


                                                                    catch (Exception ex)



                                                                    return View(user);



                                                                    1. In ViewModel put only those fields/data that you want to display on
                                                                      the view/page.

                                                                    2. Since view reperesents the properties of the ViewModel, hence it is
                                                                      easy for rendering and maintenance.

                                                                    3. Use a mapper when ViewModel become more complex.





                                                                    share|improve this answer












                                                                    • ViewModel contain fields that are represented in the view (for
                                                                      LabelFor,EditorFor,DisplayFor helpers)

                                                                    • ViewModel can have specific validation rules using data annotations
                                                                      or IDataErrorInfo.

                                                                    • ViewModel can have multiple entities or objects from different data
                                                                      models or data source.

                                                                    Designing ViewModel



                                                                    public class UserLoginViewModel 

                                                                    [Required(ErrorMessage = "Please enter your username")]
                                                                    [Display(Name = "User Name")]
                                                                    [MaxLength(50)]
                                                                    public string UserName get; set;
                                                                    [Required(ErrorMessage = "Please enter your password")]
                                                                    [Display(Name = "Password")]
                                                                    [MaxLength(50)]
                                                                    public string Password get; set;



                                                                    Presenting the viewmodel in the view



                                                                    @model MyModels.UserLoginViewModel 
                                                                    @
                                                                    ViewBag.Title = "User Login";
                                                                    Layout = "~/Views/Shared/_Layout.cshtml";

                                                                    @using (Html.BeginForm())

                                                                    <div class="editor-label">
                                                                    @Html.LabelFor(m => m.UserName)
                                                                    </div>
                                                                    <div class="editor-field">
                                                                    @Html.TextBoxFor(m => m.UserName)
                                                                    @Html.ValidationMessageFor(m => m.UserName)
                                                                    </div>
                                                                    <div class="editor-label">
                                                                    @Html.LabelFor(m => m.Password)
                                                                    </div>
                                                                    <div class="editor-field">
                                                                    @Html.PasswordFor(m => m.Password)
                                                                    @Html.ValidationMessageFor(m => m.Password)
                                                                    </div>
                                                                    <p>
                                                                    <input type="submit" value="Log In" />
                                                                    </p>
                                                                    </div>



                                                                    Working with Action



                                                                    public ActionResult Login()

                                                                    return View();

                                                                    [HttpPost]
                                                                    public ActionResult Login(UserLoginViewModel user)

                                                                    // To acces data using LINQ
                                                                    DataClassesDataContext mobjentity = new DataClassesDataContext();
                                                                    if (ModelState.IsValid)

                                                                    try

                                                                    var q = mobjentity.tblUsers.Where(m => m.UserName == user.UserName && m.Password == user.Password).ToList();
                                                                    if (q.Count > 0)

                                                                    return RedirectToAction("MyAccount");

                                                                    else

                                                                    ModelState.AddModelError("", "The user name or password provided is incorrect.");


                                                                    catch (Exception ex)



                                                                    return View(user);



                                                                    1. In ViewModel put only those fields/data that you want to display on
                                                                      the view/page.

                                                                    2. Since view reperesents the properties of the ViewModel, hence it is
                                                                      easy for rendering and maintenance.

                                                                    3. Use a mapper when ViewModel become more complex.






                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Nov 10 '18 at 7:44









                                                                    wild coder

                                                                    400713




                                                                    400713















                                                                        protected by Samuel Liew Oct 5 '15 at 9:21



                                                                        Thank you for your interest in this question.
                                                                        Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                        Would you like to answer one of these unanswered questions instead?



                                                                        Popular posts from this blog

                                                                        𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

                                                                        Crossroads (UK TV series)

                                                                        ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế