I'm fairly used to razor now, but I can't understand why the following syntax is correct?
<li @(active ? "class=active" : "")>
@Html.ActionLink(item.Text, item.TargetAction, Model.Controller)
</li>
As you can see I'm conditionally applying a class (and I've written it this way so the class tag is not generated if the bool active == false).
What I can't understand is why this then generates the correct quotes to give:
<li class="active"><a href="/">Home</a></li>
<a href="/">Home</a>
</li>
Somehow it is magically sorting out the quoting, but I can't find any reference in the articles on razor to suggest this is expected, so I'm wondering if it is relying on broken behaviour. If I add single or double quotes into the string around the word 'active', as you would expect to if cranking out html, I end up with:
<li class="'active'">
<a href="/">Home</a>
</li>
or
<li class="active">
<a href="/">Home</a>
</li>
Why does it work this way, and is my code correct (as opposed to simply functioning)?
Razor automatically HTML-escapes all code output.
You can prevent this by writing @Html.Raw(...)
Alternatively, you can put the quotes in the literal text:
<li class="@(active ? "active" : "")>
Your example works because you don't actually have any quotes.
The generated HTML source reads <li class=active>
.
Just come across this so thought would answer - SLaks looks right with Html.Raw, but the OP is also correct in that the second method doesn't look to work - the "s get encoded.
My solution was:
<li@(active ? Html.Raw(" class=\"active\"") : null)>
Just came across this bizarre behavior as well. Logically the following should work.
@(Model.IsTablet ? "data-options='is_hover: false'" : "")
but is rendered as
data-options="'is_hover:" false'=""
As Dan states this works correctly
@(Model.IsTablet ? "data-options=is_hover:false" : "")
rendering as the first example should.
data-options="is_hover:false"
but if you add a space in the attribute it breaks whatever weird stuff asp.net 4.0 is doing and it thinks your attribute ends at the space.
And this does not constitute html escaping as what is valid html syntax doesn't work and the whole point of razor is that the razor syntax should work with valid html not break it.