Robert Fall
Robert Fall

Reputation: 871

Dynamically compose ASP MVC view based on context

I have several views that are composed of several partial views based on context.

For example, we have a Project view that shows all the details of a project, which includes the scalar values, name etc, and also all the assigned employees, tasks and/or clients.

The problem I have is that certain types of project have all of the above sections while others have only two or even on section, ie. details only.

What is the best way to compose the Projects master view? I don't want to have logic to check the project in the view. Is there a way to compose a view in code by programatically rendering the relevant partials and ignoring the rest?

Otherwise are there any other ideas how to do this in a maintainable way? I could of course just render the partials using if statements to check if they apply, but that way the view contains VERY important logic. In another situation we want to use this method to display content based on the type of subscription a user has.

Thanks!

Upvotes: 1

Views: 284

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039368

I would stick with the if approach. To avoid coding important logic in the view define properties in your view model and let the controller set the value so that inside the view you only have:

<% if (Model.HasDetails) { %>
    <% Html.RenderPartial("details"); %>
<% } %>

Or if you are working with display/editor templates you could simply:

<%= Html.DisplayFor(x => x.Details) %>

Upvotes: 1

Related Questions