简体   繁体   中英

How to add multiple model in a single view?

I have 3 models. 1 model am using for the search box rest 2 I am using for display the checkbox list.

for search box I don't want Ienumerable type model but for checkbox I want Ienumerable type model

Data is coming from different controller How can I do this in a single view?

Please give some example.

Make ViewModel then send your ViewModel to view after setting properties;

    public class MyModel1 {}

    public class MyModel2 {}


    public class ViewModel
    {
     public MyModel1 MyModel1 {get; set;}
     public MyModel2 MyModel2 {get; set;}
    }

Then in your view after setting @model ViewModel you can use any sub models you want like @Model.MyModel1 etc

If you want to use 3 models in a view, you have to declare a "Bag" view model where you wrap all submodels that you want to use.

First, if you must create your submodels, if you haven't then you include them in the bag view model.

    public class FirstViewModel 
    {
      public int MyProperty { get; set; }
    }

    public class SecondViewModel 
    {
      public string MySecondProperty { get; set; }
    }

    public class ThirdViewModel 
    {
      public DateTime MyThirdProperty { get; set; }
    }

    public class BagViewModel
    {
      public FirstViewModel FirstModel { get; set; }

      public SecondViewModel SecondModel { get; set; }

      public ThirdViewModel ThirdModel{ get; set; }
    }

The submodels can be either view or binding models.

And in your razor view, you include the BagViewModel:

    @model BagViewModel

Then if you want to use FirstViewModel ( for example ), you do it with:

    @Model.FirstViewModel

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