tags:

views:

383

answers:

2

I am wondering if there are any known issues with adding a ViewUserControl at run time (to a ViewPage). It works fine if I add the control declaritively but not if I add the control programmatically (in the code behind file in this case). I don't get an error, it just does not render the control but stepping through the debugger does confirm that the relevant methods in the page life cycle are being called.

I do realize that it's not quite kosher to use a code behind file with ASP.NET MVC but I do have reasons for wanting to do so.

+5  A: 

Send the list of controls you want to load and pass it to the view model.

Controller action:

var controlsToLoad = new List<string>();
controlsToLoad.Add("foo");

return View(controlsToLoad);

View:

<% foreach (var control in Model as List<string>) { %>
    <% Html.RenderPartial(control); %>
<% } %>

This will keep you out of code behind and still let you dynamically specify in the controller which controls to load in the view.

John Sheehan
Hi John,Thanks for a quick response. Is this the only way to do it? I'd like to be able to create an arbitrary number of instances of a certain PartialView class, each with different data.
Rodrick Chapman
Create a DTO with two properties: string ControlName and object Data then create the list of those and in the loop use RenderPartial(ControlName, Data); to pass the control-specific data.
John Sheehan
A: 

Or you can get slicker and wrap the above suggestion in an extension method to your ViewPage class an extension method if you need other functionality.

Wyatt Barnett