views:

54

answers:

2

I find myself writing a lot of code in my views that looks like the code below. In this case, I want to add some explanatory HTML for a novice, and different HTML for an expert user.

<% if (ViewData["novice"] != null ) { %>
some extra  HTML for a novice
<% } else { %>
some HTML for an expert
<% } %>

This is presentation logic, so it makes sense that it is in a view vs the controller. However, it gets ugly really fast, especially when ReSharper wants to move all the braces around to make it even uglier (is there a way to turn that off for views?).

My question is whether this is proper, or should I branch in the controller to two separate views? If I do two views, I will have a lot of duplicated HTML to maintain.

Or should I do two separate views with a shared partial view of the stuff that is in common?

+1  A: 

You're trying to create 2 completely separate html pages with identical models. You want a separate view. Don't try to out clever the design pattern with conditional-branching logic.

HTML helpers aren't going to help you much here, since it appears you will not be repeating much logic other than if else.

Jace Rhea
All I can say I even with out having repeating logic I would prefer to use a helper instead of duplicating code. Duplication of code just causes maintenance headaches and should be frowned upon
John Hartsock
I don't think you want a separate view as it would create an additional maintenance overhead. I would be more inclined to push the logic back to the controller and have a single clean view
lomaxx
You can put repeating code in partials, but big picture it seems like you want two separate views, i.e. "different HTML for an expert user" Repeating code is bad, working against a design pattern is worse IMO.
Jace Rhea
+2  A: 

Ideally, this kind of logic would be handled in the view model and the view should just be rendering the model.

So you might have something like in your view:

<%= ViewData["helptext"]  %>

and your logic in the controller would be something like:

ViewData["helpText"] = isNovice ? noviceText : expertText;

that way you can push that logic back to the controller and keep your views nice and clean

lomaxx
I can see the advantage of this, but what if the text is complex HTML markup, say with images and stuff? Now you have HTML in your controller.Also, thanks for fixing my code example
Alex Kilpatrick
Nice lomax much better. I like it. +1
John Hartsock
It depends what the situation is with the complex text and how much change is required, but I don't see why the same approach can't be used to render the variable portions?
lomaxx
If it's *really* complex, you also might be able to break it out into a partial view
lomaxx