5

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!)

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
Paul Hiles
  • 9,558
  • 7
  • 51
  • 76
  • If you're using Razor, try googling "Razor Declarative HTML helpers" they might suit your situation... they might not. But their new and funky ;-) – Charlino Mar 16 '11 at 20:21

3 Answers3

4

IMHO logic like this is fine for a view:

@if (Model.ShouldShowSomeSection)
{
    ... some large chunk of HTML
}
else
{
    ... some alternative
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
4

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
bmancini
  • 2,028
  • 15
  • 21
0

I agree with the answer from @bmancini , but here's what I'd do slightly differently:

I would logically group those 'several html chunks to render' into different partial views :

 _partialViewA.cshtml and _partialViewB.cshtml 

I then would use extension methods and have my logic in a Helpers folder, then Html sub-folder like this:

    using System.Web.Mvc.Html;

    public static class SomeViewHelper
    {
        public static MvcHtmlString OutputHtmlString(this HtmlHelper helper , SomeModel model)
        {
          if(model.HasA)
          {
            return helper.Partial("_partialViewA", model)
          }
          if(model.HasB)
          {
            return helper.Partial("_partialViewB", model)
          }
        }   
    }

This would remove all the logic from the view which would now only have this code:

    @Html.OutputHtmlString(Model);

At least this would remove the 'ugliness' and avoid the conditional statements, and also avoid 'escaping the html chinks in C# code'... Of course I would have to reference the Helpers.Html folder with a @using statement in the view.

Ken.Fukizi
  • 197
  • 1
  • 9