How to control conditional display of partial views in ASP.NET MVC

In our standard ASP.NET solution web forms, we typically place a set of user controls on the main page and determine whether they appear or not in their code. What is the best approach in ASP.NET MVC to achieve the same goal?

Obviously, you could use if statements on the main page or partial view, but this seems useless to me and violates the principle of preserving business logic from the view. It also requires either the placement of the necessary information in all viewing models, or inheritance from the base controller, which seems to be very much in demand for something so simple.

I was thinking about using RenderAction and returning a completely empty view to prevent any output - is this a good template?

+6
asp.net-mvc
source share
2 answers

violates the principle of maintaining business logic from a view

This is not business logic. This is the logic of the presentation when you decide whether to display something or not. This is normal there.

You can decide whether to show something or not, and set up several flags in the model (for example, you can make BaseModel or MasterModel). Then your main views, partial views themselves, or HTML helpers will conditionally render based on these flags.

As for the pure separation of problems, yes, WebForms could do this, but it was a pretty big abstraction of the underlying mechanisms. Often this leads to the fact that business logic makes sense in the code, that is, in the presentation layer, where the business logic belongs to nothing more than representations.

+3
source share

You could avoid the messy If statements by creating an Html extension method, as mentioned in my recent post http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering-partial-views/

Thanks,

Rajeesh

+1
source share

All Articles