In a tag I want to conditionally output the style attribute, e.g.: <li style="@styleVar" >...</li>
When styleVar is null it should not be written by razor (just the supposed standard functionality in Razor 2), but for some strange reason it is outputted as <li style="">...</li>
, while I expect <li>...</li>
.
This is in a partial view. In a normal view it is working. So is this a bug in partial views?
Anybody the same experience?
This does not seem to work in partial views and for custom html attributes such as data-test="@test". This is not omitted, instead it still puts in the data-test="". So the MVC team has to fix this asap.
If the styleVar
is equal to null
(not the string.Empty
) mvc4 will automatically do this.
Conditional attribute rendering
If you have an attribute that might be null, in the past you've needed to do a null check to avoid writing out an empty attribute, like this:
<div @{if (myClass != null) { <text>class="@myClass"</text> } }>Content</div>
Now Razor is able to handle that automatically, so you can just write out the attribute. If it's null, the attribute isn't written:
<div class="@myClass">Content</div>
So if @myClass is null, the output is just this:
<div>Content</div>
Don't see any error in your code: you "hard code" markup and vary only style value. To achieve what you are trying to do, you need code similar to this:
@if(!string.IsNullOrEmpty(styleVar))
{
<li style="@styleVar" >...</li>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With