我需要在 MVC Razor 中编码属性值吗? [英] Do I need to encode attribute values in MVC Razor?

查看:16
本文介绍了我需要在 MVC Razor 中编码属性值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个 cshtml 文件中,我将一个字符串分配给一个属性.例如:

In a cshtml file, I'm assigning a string to an attribute. For example:

<input name="somename" value="@Model.Value">

由于@Model.Value 字符串可以包含任何Unicode 字符,显然该字符串必须被编码.Razor 会自动编码这个值吗?我猜它不会或不能,因为我可以轻松地在它之后立即放置一个 @Html.Raw 以将整个内容分解为两个标签.

Since @Model.Value string could contain any Unicode character, obviously the string must be encoded. Will Razor encode this value automatically? I'm guessing it won't or can't because I could easily put a @Html.Raw immediately after it to break up the whole thing into two tags.

我认为我需要做的是:

<input name="somename" value="@Html.Raw(Html.AttributeEncode(Model.Value))">

正确吗?

同样,如果我在脚本的 JavaScript 字符串中嵌入一个字符串值,我应该使用:

Likewise, if I'm embedding an string value in a JavaScript string in a script, should I use:

//I could use Ajax instead of HttpUtility here, but Ajax just wraps the same call.
<script>$('id').data('key','@Html.Raw(HttpUtility.JavaScriptStringEncode(Model.Value))');</script>

推荐答案

Razor 默认对字符串执行 HTML 编码.根据您的字符串被注入 HTML 流的位置,这可能是也可能不是要使用的正确编码.如果它不是正确的编码,那么您需要自己执行正确的编码,并确保返回一个 MvcHtmlString(即 IHtmlString)以确保 Razor 不影响您的自定义编码.

Razor performs HTML encoding on strings by default. Depending on where your string is being injected into the HTML stream, this may or may not be the correct encoding to use. If it's not the correct encoding, then you need to perform the correct encoding yourself and be sure to return an MvcHtmlString (i.e. an IHtmlString) to ensure Razor leaves your custom encoding alone.

由于 Razor 使用 HTML 编码,这在技术上与 HTML 属性编码不同(它是一个子集),因此使用 @Html.Raw(Html.AttributeEncode(Model.Value)) 对值进行 HTML 属性编码并没有错.同时,这也不是必需的,因为默认的 HTML 编码使用相同的基本格式,并且最终只会编码几个不需要在 HTML 属性值中编码的字符.

Since Razor uses HTML encoding, which is technically different from HTML attribute encoding (it's a subset), it's not wrong to use @Html.Raw(Html.AttributeEncode(Model.Value)) to HTML attribute encode the value. At the same time, it's also not necessary, since the default HTML encoding uses the same basic format and will just end up encoding a couple character that otherwise wouldn't need encoded in an HTML attribute value.

另一方面,在将字符串注入到 JavaScript 字符串的引号中的最后一种情况下,HTML 编码绝对不正确,因此您肯定需要像我一样自己执行编码:@Html.Raw(HttpUtility.JavaScriptStringEncode(Model.Value)).

On the other hand, in the final case where a string is being injected into the quotes of a JavaScript string, the HTML encoding would absolutely be incorrect, so you'd definitely need to perform the encoding yourself as I did: @Html.Raw(HttpUtility.JavaScriptStringEncode(Model.Value)).

这篇关于我需要在 MVC Razor 中编码属性值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆