If I wanted multiple if statements in an html attribute I might do something like this:
<input type="button" value="Bad, the title has a lot of excess spacing" title="@if(SomeModel.condOne) {
<text>this</text>
}
@if (SomeModel.CondTwo)
{
<text> is</text>
}
@if (SomeModel.CondThree)
{
<text> a title</text>
}
" />
But that creates a lot of empty spaces that need truncating. So this works:
<input type="button" value="Good, the title is condenced" title="@if(SomeModel.condOne) {<text>this</text>}@if (SomeModel.CondTwo){<text> is</text>}@if (SomeModel.CondThree){<text> a title</text>}" />
The same principle can be applied to an element with multiple classes (e.g. class=”oddrow class1″ -> class=”evenrow class2″)
But that might be hard to read if it’s a long line. And visual studio has a habit of breaking that statement into multiple lines if you touch the bracket or Ctrl-K,Ctrl-D (which any next developer is likely to do).
Is there a better or more fullproof way to implement multiple attribute conditions in a line for MVC razor?
I suggest creating a small helpers method that returns the text you need.
You’d have to pass it
SomeModeland inside that method check for your condition that way you’d have something nicer to look at and easier to maintain.For example:
You can read all about Html Helper methods here on Jon Galloway’s blog.
That’s where I learned how to use them.