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

查看:50
本文介绍了我是否需要在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天全站免登陆