问题
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?
回答1:
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.
回答2:
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>
回答3:
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>
}
回答4:
Another possible cause is a Razor comment within the HTML tag.
// This renders <div>Hello world</div>
<div class="@null">Hello world</div>
// Renders <div class="">Hello world</div>
<div @**@ class="@null">Hello world</div>
I ran into this when I had commented out a single attribute for testing purposes and all of the sudden my conditional attributes were broken.
回答5:
I have just had a situation where a space between an attribute name and the equals sign broke boolean conditional rendering:
So
<input type="checkbox" name="fieldname" id ="fieldname" checked="@Model.MyBool" />
rendered with checked="True"
, whereas
<input type="checkbox" name="fieldname" id="fieldname" checked="@Model.MyBool" />
rendered correctly with checked="checked"
The conditional rendering appears fairly brittle.
This isn't exactly an answer to the detail of the OP's question, but it's definitely a possibility for people who are looking for help with "Razor conditional attribute not working"
回答6:
When styleVar == null
you will get <li style="">...
(at least with mvc3) in partial and normal views.
I guess you have to use the conditional operator:
<li @(styleVar == null ? "" : "style=\"" + styleVar + "\"")>...</li>
来源:https://stackoverflow.com/questions/13267619/razor-conditional-attribute-not-working