对于一个项目,我使用 jqote 在 JavaScript 和 HTML 中进行模板化,由 MVC 4 和 Razor 生成。
请在 HTML 和 Razor 中查看以下代码:
<script id="testTemplate" type="text/html">
<p>Some html</p>
@{string id = "<%=this.Id%>";}
<!-- 1 -->
@if(true)
{
@Html.Raw(@"<select id="""+id+@"""></select>")
}
<!-- 2 -->
@if(true)
{
<select id="@Html.Raw(id)"></select>
}
<!-- 3 -->
@Html.Raw(@"<select id="""+id+@"""></select>")
<!-- 4 -->
<select id="@Html.Raw(id)"></select>
<!-- 5 -->
<select id="<%=this.Id%>"></select>
</script>
输出是这样的:
<script id="testTemplate" type="text/html">
<!-- 1 -->
<select id="<%=this.Id%>"></select> <!--Good!-->
<!-- 2 -->
<select id="<%=this.Id%>"></select> <!--BAD!-->
<!-- 3 -->
<select id="<%=this.Id%>"></select> <!--Good!-->
<!-- 4 -->
<select id="<%=this.Id%>"></select> <!--Good!-->
<!-- 5 -->
<select id="<%=this.Id%>"></select> <!--Good!-->
</script>
现在,问题在于
<!-- 2 -->
下的第二个选择.人们会期待 Html.Raw
在这里踢,但不知何故它没有。或者 Razor 想要对其中的内容进行 HtmlEncode。问题是:有谁知道为什么?这是错误还是设计使然?
如果没有脚本标签,它就可以工作。但是我们需要脚本标签,因为我们需要在 JavaScript 中进行模板化。
硬编码它有效,但我们需要使用一个变量,因为它并不总是一个模板。
没有
@if
它有效,但它就在那里,我们需要它。解决方法
这些行给出了类似的良好输出:
@if(true)
{
<select id= "@Html.Raw(id)"></select>
}
@if(true)
{
<select id ="@Html.Raw(id)"></select>
}
@if(true)
{
<select id @Html.Raw("=")"@Html.Raw(id)"></select>
}
我们打算这样做:
<script id="testTemplate" type="text/html">
@{string id = @"id=""<%=this.Id%>""";}
@if(true)
{
<select @Html.Raw(id)></select>
}
</script>
...尽可能保持标记完整。
最佳答案
编辑 阅读正确提供的代码后:
这看起来像一个错误。它以某种方式连接到 id 属性。将属性更改为其他内容即可。
@if(true)
{
<select data-id="@Html.Raw(id)"></select>
}
显然这不是解决方案,只是验证。您的示例 4 或多或少暗示它不是设计使然,否则它也会失败。
关于razor - 如何使 MVC 4 Razor Html.Raw 在脚本标签内的 HTML 中赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13605745/