ASP.NET MVC dynamic view sections

Edit on GitHub

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 2 { 3 public List<dynamic> SettingsSections = new List<dynamic>(); 4 }

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 2 3 @{ 4 ViewBag.Title = "Index"; 5 } 6 7 <h2>Settings</h2> 8 9 @foreach (var item in Model.SettingsSections) 10 { 11 @Html.DisplayFor(model => item); 12 }

This is an imported post. It was imported from my old blog using an automated tool and may contain formatting errors and/or broken images.

Leave a Comment

avatar

3 responses

  1. Avatar for Edgar Ochieng&#39;
    Edgar Ochieng&#39; September 11th, 2011

    What if you have two models like Agenda and Day. Agenda has a DayID item. I want to list the every day&#39s agenda in the following format:

    Day 1
    -------Agenda Item 1
    -------Agenda Item 2
    -------Agenda Item 3

    Day 2
    -------Agenda Item 1
    -------Agenda Item 2
    -------Agenda Item 3

  2. Avatar for maartenba
    maartenba September 12th, 2011

    Use a regular ViewModel / View or the approach outloned in this post and adjust the DisplayTemplate (or EditorTemplate) for the Agenda

  3. Avatar for David
    David November 8th, 2011

    A nice find Maarten - what would be interesting to know is how a Model of List<dynamic> - that consists of editable fields can be processed by the Post Action (and understand what each of the indivdual Sections it contain map to for persitence). I am presuming that the type of the Model passed back to the Action is also List<dynamic> ...?

    I tried a very simple test that posted back from a UI rendered from List<dynamic> and the data is indeed posted, but is not reconstructed back into the List<dynamic>, as obviously it does not know what to recompose...