Guest User

Untitled

a guest
Mar 20th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. //ModelCollection.cs in models
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5.  
  6. namespace ModelContainer
  7. {
  8. public class ModelCollection
  9. {
  10. private Dictionary<Type, object> models = new Dictionary<Type, object>();
  11.  
  12. public void AddModel<T>(T t)
  13. {
  14. models.Add(t.GetType(), t);
  15. }
  16.  
  17. public T GetModel<T>()
  18. {
  19. return (T)models[typeof(T)];
  20. }
  21. }
  22. }
  23.  
  24. //Controller:
  25. public class SampleController : Controller
  26. {
  27.  
  28. ModelCollection modelCollection = new ModelCollection();
  29. public ActionResult Index()
  30. {
  31. var model1 = new Model1();
  32. var model2 = new Model2();
  33. var model3 = new Model3();
  34.  
  35. // Do something
  36.  
  37. modelCollection.AddModel(model1);
  38. modelCollection.AddModel(model2);
  39. modelCollection.AddModel(model3);
  40. return View(modelCollection);
  41. }
  42.  
  43. public ActionResult SaveModels(ModelCollection modelCollection)
  44. {
  45. //code here
  46. modelCollection is empty, why???
  47.  
  48. }
  49.  
  50. //The View:
  51. @using Models
  52. @model ModelCollection
  53.  
  54. @{
  55. ViewBag.Title = "Model1: " + ((Model.GetModel<Model1>()).Name);
  56. }
  57.  
  58. <h2>Model2: @((Model.GetModel<Model2>()).Number</h2>
  59.  
  60. @((Model.GetModel<Model3>()).SomeProperty
Add Comment
Please, Sign In to add comment