Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //ModelCollection.cs in models
- using System;
- using System.Collections.Generic;
- namespace ModelContainer
- {
- public class ModelCollection
- {
- private Dictionary<Type, object> models = new Dictionary<Type, object>();
- public void AddModel<T>(T t)
- {
- models.Add(t.GetType(), t);
- }
- public T GetModel<T>()
- {
- return (T)models[typeof(T)];
- }
- }
- }
- //Controller:
- public class SampleController : Controller
- {
- ModelCollection modelCollection = new ModelCollection();
- public ActionResult Index()
- {
- var model1 = new Model1();
- var model2 = new Model2();
- var model3 = new Model3();
- // Do something
- modelCollection.AddModel(model1);
- modelCollection.AddModel(model2);
- modelCollection.AddModel(model3);
- return View(modelCollection);
- }
- public ActionResult SaveModels(ModelCollection modelCollection)
- {
- //code here
- modelCollection is empty, why???
- }
- //The View:
- @using Models
- @model ModelCollection
- @{
- ViewBag.Title = "Model1: " + ((Model.GetModel<Model1>()).Name);
- }
- <h2>Model2: @((Model.GetModel<Model2>()).Number</h2>
- @((Model.GetModel<Model3>()).SomeProperty
Add Comment
Please, Sign In to add comment