8. September 2011 08:26
ASP.NET . C# . General . MVC
Earlier today, a colleague of mine asked for advice on how he could create a “dynamic” view. To elaborate, he wanted to create a change settings page on which various sections would be rendered based on which plugins are loaded in the application.
Intrigued by the question and having no clue on how to do this, I quickly hacked together a SettingsViewModel, to which he could add all section view models no matter what type they are:
1 public class SettingsViewModel
3 public List<dynamic> SettingsSections = new List<dynamic>();
To my surprise, when looping this collection in the view it just works as expected: every section is rendered using its own DisplayTemplate. Simple and slick.
1 @model MvcApplication.ViewModels.SettingsViewModel
4 ViewBag.Title = "Index";
9 @foreach (var item in Model.SettingsSections)
11 @Html.DisplayFor(model => item);