1

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.