Multiple models in a view

前端 未结 12 1842
太阳男子
太阳男子 2020-11-21 23:07

I want to have 2 models in one view. The page contains both LoginViewModel and RegisterViewModel.

e.g.

pub         


        
12条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 23:39

    Add this ModelCollection.cs to your Models

    using System;
    using System.Collections.Generic;
    
    namespace ModelContainer
    {
      public class ModelCollection
      {
       private Dictionary models = new Dictionary();
    
       public void AddModel(T t)
       {
          models.Add(t.GetType(), t);
       }
    
       public T GetModel()
       {
         return (T)models[typeof(T)];
       }
     }
    }
    

    Controller:

    public class SampleController : Controller
    {
      public ActionResult Index()
      {
        var model1 = new Model1();
        var model2 = new Model2();
        var model3 = new Model3();
    
        // Do something
    
        var modelCollection = new ModelCollection();
        modelCollection.AddModel(model1);
        modelCollection.AddModel(model2);
        modelCollection.AddModel(model3);
        return View(modelCollection);
      }
    }
    

    The View:

    enter code here
    @using Models
    @model ModelCollection
    
    @{
      ViewBag.Title = "Model1: " + ((Model.GetModel()).Name);
    }
    
    

    Model2: @((Model.GetModel()).Number

    @((Model.GetModel()).SomeProperty

提交回复
热议问题