Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional logic in mvc view vs htmlhelper vs action

I have a large view that needs some conditional logic to decide which of several html chunks to render in the middle of the view. I have a property on my model which can have several different values which determines the html to be output.

I would normally put conditional logic in an html helper, but given that each output is a fair chunk of html, I am not sure that escaping these in a c# file would be great. I could also put the logic in the action and render different views but given that the majority of the view is the same, this does not seem great either. So I am left with multiple if statements in my view (or partial?) which also seems ugly (and is obviously untestable).

What is the best way of doing this?

(I am using MVC3 in case there is something new and funky I can use!)

like image 225
Paul Hiles Avatar asked Mar 16 '11 17:03

Paul Hiles


1 Answers

I usually put separate visual chunks in their own partials. Then my view conditionally calls each partial with Html.Partial. This keeps you main view from bloating.

In general, I try to avoid Html.Helpers that contain more than a single element.

Something like:

@if(Model.HasA) 
{
    @Html.Partial("widgetdetails-hasa")
}

@if(Model.HasB)
{ 
    @Html.Partial("widgetdetails-hasb")
}
// etc
like image 60
bmancini Avatar answered Oct 03 '22 20:10

bmancini