Razor conditional attribute not working

一曲冷凌霜 提交于 2019-12-05 17:15:07

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>
}

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.

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"

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!