简体   繁体   中英

Understanding model use in view

Consider the following code snippet

public class FirstViewModel
{
    public IEnumerable<SelectListItem> GetSomeData()
    {
      //query dbcontext here
    }
}

public class SecondViewModel
{
    public Employee Employee { get; set; }
    public Stock Stock { get; set; }
    //more properties
}

So with the first snippet I can do the following in my code:

@Html.DropDownListFor(model => Model.Employee, new App.Models.ViewModels.FirstViewModel().GetSomeData(), "Please choose something")

In the second snippet I can do:

@Html.DropDownListFor(model => Model.Employee, new SelectList(Model.Employee), "Select Status")

What I'm trying to achieve is to have multiple models in one view for my MVC app. My question is would it be better to have a separate view model for each or one big view model which reference all other models. I'm very new to MVC so any help would be appreciated.

Each of my Views has a ViewModel - that may be an aggregate of two VMs (as properties). Important to remember the VM is a Model for the View - its not a Data Model in its own right. The data model should be elsewhere and the Controller maps between the two.

(I've never had a ViewModel actively pull data from a DB before - I've always had the Controller populate the ViewModel. Not directly related to your question, but important to go in the right direction from the start.)

I would base it on use. If you need all of the data all of the time why not include it all.

Other things to consider:

  1. Do you need all of the data all the time?
  2. Are there maximums to worry about for reads?
  3. Possible memory limitations?
  4. Number of visits/traffic load considerations.

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