首页 > 解决方案 > 为什么 Razor 在 html 元素上设置的条件样式总是 html 编码不正确

问题描述

使用 razor 有条件地在 html 元素上设置样式始终将 ' 字符编码并呈现为 ' ; (这会产生不正确的 html 并意味着浏览器不会呈现应用的样式。

我尝试了以下方法:

<tr ID="Question-Answer-@(item.QuestionID)" @(!firstItem ? Html.Raw("style=\'display: none\'").ToString() : "" )>   
<tr ID="Question-Answer-@(item.QuestionID)" @(!firstItem ? HttpUtility.HtmlDecode("style=\'display: none\'") : "" )>
<tr ID="Question-Answer-@(item.QuestionID)" @(!firstItem ? "style=\'display: none\'" : "" )>
<tr ID="Question-Answer-@(item.QuestionID)" @(!firstItem ? "style='display: none'" : "")>
<tr ID="Question-Answer-@(item.QuestionID)" @(!firstItem ? new HtmlString("style=\'display: none\'").ToString() : "" )>     

两个代码示例都产生以下内容:

<tr ID="Question-Answer-2" style=&#39;display: none&#39;>
and I need:
<tr ID="Question-Answer-2" style='display: none'>

标签: c#htmlcssrazor

解决方案


这是我的问题的答案:

<tr ID="Question-Answer-@(item.QuestionID)" @{if (!firstItem) { <text> style='display: none' </text> } }>

(nb。我仍然不明白为什么我上面尝试的 5 种不同的方法不起作用)


推荐阅读