Just started converting to MVC from classic ASP and wondering about best practice for if-statements that is used to decide if a HTML-element should be visible or deciding if that or that HTML-element should be visible.
Example:
if (type = 1)
{
<img src="/Content/Images/gray.jpg" />
}
else
{
<img src="/Content/Images/blue.jpg" />
}
I see several options here.
1. Use if-statements in my views (prefer not to)
2. Use a HTML-helper (will be a lot of helpers = Hard to work with the code)
3. Create HTML-snippets in my controller and pass into my view
4. Work with JavaScript to show/hide element on document load.
The example above if of course a simplification of my problem. Many thanks for the help!
/Mike
EDIT:
Took a bad example, here comes a new:
if (type = 1)
{
<span class="class1">Something something</span>
}
else
{
<div id="id1">
text
<img src="/Content/Images/gray.jpg" />
</div>
}
I personally prefer to use HtmlHelper extensions or declarative HTML helpers for all but most trivial conditional expressions. However in this case I would probably let my laziness win, and express the conditional directly in the view like so:
Edit
For more complex scenarios, definitely HTML helpers. If you’re using the Razor syntax, you can create declarative helpers by placing them into your ~/Views/Helpers directory. They’re very clean to write and use.
But the idea behind creating a good helper is that it encapsulates an intention. This is easy to test by trying to give your helper a name. If the name is
IfOneThenShowSomethingElseGrayImage, you should try to break it into further pieces still.So let’s imagine the intention in your example is to show information about the current user based on the user type. You could create a helper like this:
And then use it in your view like this:
Even though it’s only used on one page, it enhances the readability in the view, and can be reused if necessary.
Just my two cents.