Logo

Maarten Balliauw {blog}

ASP.NET, ASP.NET MVC, Windows Azure, PHP, ...

About the author

Maarten Balliauw is currently employed as a Technical Evangelist at JetBrains. His interests are mainly web applications developed in ASP.NET (C#) or PHP and the Windows Azure cloud platform.
More about me More about me
Send mail E-mail me


ASP.NET MVC Quickly Pro NuGet Subscribe to my RSS feed Follow me on Twitter! View Maarten Balliauw's profile on LinkedIn
Maarten Balliauw - MVP - Most Valuable Professional
Maarten Balliauw - ASPInsider

Search

Archive

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright Maarten Balliauw 2013


ASP.NET MVC dynamic view sections

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 }

Categories: ASP.NET | C# | General | ICT | MVC

Comments (3) -

Edgar Ochieng' Kenya |

Sunday, September 11, 2011 1:14 PM

Edgar Ochieng&#39;

What if you have two models like Agenda and Day. Agenda has a DayID item. I want to list the every day's 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

maartenba Belgium |

Monday, September 12, 2011 8:24 AM

maartenba

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

David Netherlands |

Monday, November 07, 2011 7:32 PM

David



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...

Pingbacks and trackbacks (4)+

Comments are closed