简体   繁体   中英

Two ViewModels for one View

I am developing a Web-App using ASP.NET MVC and I've been trying to avoid using the ViewBag, therefore I created few viewmodels to populate my drop-downs and in general to pass the data I need in my views. At the same time I would like to keep the data binding clean and avoid properties that will not be bound to (without using include/exclude attributes) and I've been told that obviously returnmodels are great for that purpose.

So is creating two independent models for one view a bad idea? One with all the data that needs to be displayed and another one only with the fields from my form or is this an excess of form over substance and should I reconsider changing my design?

Edit: A quick example because I'm not too good at explaining

class ViewModelA{ // passed to the view and then bound to when form is submitted
    List<KeyValuePair<int, string>> DropDownValues; // will be always empty while databinding
    int SelectedValue; // will be always 0 when passed to the view
    ...
}

Should I replace ViewModelA with

class ViewModelB{ // contains data passed to the view
    List<KeyValuePair<int, string>> DropDownValues;
    ...
}


class ReturnModel{ // contains data returned from the view
    int SelectedValue;
    ...
}

Obviously here I could just bind directly to my model but let's assume it's more complex and the data has to be processed before saved.

I think I know what you are asking. You are saying you have a viewmodel with, lets say, these properties: Age, Name, CountryOfResidence (for dropdown), and a few more properties. But when you create a new person, you only post Age, Name, IdOfCountry to controller.

So your question is what is the point of posting the whole viewmodel, when it is not needed. Fair question.

There are many ways you can do this. Here is one way:

  1. Create a base class with common properties (for posting)
  2. Create a derived class with more properties for the view.

Some people will refer to 1 as Data Transfer Object (DTO). These DTO's will be shared for communication between presentation layer, service layer, business layer, data access layer etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM