Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor conditional attribute not working

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?

like image 347
Jaap Avatar asked Nov 07 '12 10:11

Jaap


3 Answers

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.

like image 188
lymber Avatar answered Oct 17 '22 06:10

lymber


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>
like image 6
Chamika Sandamal Avatar answered Oct 17 '22 07:10

Chamika Sandamal


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>
}
like image 1
Dima Avatar answered Oct 17 '22 05:10

Dima