ViewModel and MVCViewModel in MVC

Source: Internet
Author: User

ViewModel and MVCViewModel in MVC

The ViewModel concept is not only available in the MVC model. You will see it in many articles about MVC, MVP, and MVVM, and this concept may be mentioned in any technology, for example, ASP. NET, Silverlight, WPF, or MVC... now let's discuss how to use it in MVC.

What is ASP. net mvc ViewModel?

In general, when we pass data to the View, it is a Model. When there is some additional data, we will use viewbag and so on, however, we can use ViewModel to integrate these together, that is, ASP. net mvc ViewModel allows you to integrate one or more data models and resources into one object, so that the View can be optimized when using the model. The following figure shows the concept of ViewModel:

ViewModel is used to render a single View object. On the other hand, it can reduce the logic code displayed in the UI. This is necessary, that is to say, the only task of View is to render a single ViewModel object. In order to ensure a clear separation between the concerns, decoupling means that your program is better designed, therefore, we need to place the data processing code in the proper position, away from View and controller.

 

Using ViewModel in MVC makes it easier to separate program components and maintain them. Remember, unit testing refers to testing small units. The following lists when you want to use ViewModel:

1. inconfigurating dropdown lists of lookup data into a related entity

2. Master-detail records view Pagination:

3. combining actual data and paging information

4. Components like a shopping cart or user profile widget

5. Dashboards with multiple sources of disparate

6. data Reports, often with aggregate data

Create ViewModel

Although Viewmodel contains several entities, it is only a class and there is nothing special about it. The position where it is placed can be:

1. In a folder named ViewModels, this folder can be placed in the root directory of the project;

2. As a dll, We reference it from the MVC project;

3. Put the service layer in a separate project;

The first method is undoubtedly the simplest one. We only need to create a folder and then create a class.

To create a CustomerViewModel, we need to take the Customer and StateDirctionary types as attributes to form a CustomerViewModel class. The Code is as follows:

public class CustomerViewModel {     public Customer Customer { get; set; }     public StatesDictionary States { get; set; }     public CustomerViewModel(Customer customer)     {         Customer = customer;         States = new StatesDictionary();     } }

Send ViewModel to Veiw

Of course, we started from the Controller and sent the ViewModel to the View, which is the same as sending the common model to the View, because the ViewModel is just a class, the View does not know where the model or viewModel comes from. You can create a ViewModel instance in the controller. To ensure the cleanliness of the controller, there is no additional code, in Controller, you only need to obtain the value of the model or ViewModel. Nothing else:

public ActionResult Edit(int id) {      Customer customer = context.Customers.Single(x => x.Id == id);      var customerViewModel = new CustomerViewModel(customer);      return View(customerViewModel); }

Then the view is used to render the ViewModel.

In order to let the View know which object we passed in, we need to point the @ model keyword to the ViewModel, just as you are specifying a general model.

@model FourthCoffee.Web.ViewModels.CustomerViewModel

Code for calling data:

<div class="editor-label">   
  @Html.LabelFor(model => model.Customer.FirstName) </div>
<div class="editor-field"> @Html.EditorFor(model => model.Customer.FirstName) @Html.ValidationMessageFor(model => model.Customer.FirstName)
</div>@* ...View code continues rendering properties...

Tips for using ViewModel:

1. Manual viewing is required when ViewModel is used. However, when ViewModel is complex, this will become more difficult, we can simply use AutoMapper to simplify the work. AutoMapper will allow you to smoothly create mappings between ViewModel and models, in addition to POCO Generator and ef poco Templates.

2. Only put the attributes you used for rendering on the View into the ViewModel.

3. Use View to guide the creation of ViewModel attributes, so that rendering and maintenance can be better.

The above motion graphs are provided by "Graph dado ".

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.