如何在 Html.TextBoxFor 方法中为 javascript 添加单引号?
我正在尝试在 Html.TextBoxFor 方法中添加一个 javascript 方法作为自定义属性,如下所示:
<%: Html.TextBoxFor(model => model.DateCreated, new { size="15", onfocus="myObject.myFunction(this, 'DateCreated');return false;"}) %>
我遇到的问题是单引号字符正在被 html 编码,这是我对 < 的期望;%:
。有没有办法阻止该片段的 html 编码(例如使用 \ 来转义字符串中的字符)?是否有其他方法添加此自定义属性?或者我只是干脆做错了?
I am attempting to add a javascript method as a custom attribute in an Html.TextBoxFor method like this:
<%: Html.TextBoxFor(model => model.DateCreated, new { size="15", onfocus="myObject.myFunction(this, 'DateCreated');return false;"}) %>
The problem I'm experiencing is that the single quote characters are being html encoded, which is an expection I have of the <%:
. Is there a way to prevent the html encoding for just that piece (like using a \ to escape characters in strings)? Is there a different method of adding this custom attribute? Or am I just flat out doing this wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
即使引号被编码,你的 JavaScript 也应该可以工作。例如,以下代码片段会提示正确的文本:
实现此目的的另一种方法是使用不显眼的 javascript,并且不要将标记与 script: 混合
,然后使用 jquery 在单独的 javascript 文件中:
Even if the quotes are being encoded your javascript should work. For example the following snippet alerts the correct text:
Another way to achieve this is to use unobtrusive javascript and not mix markup with script:
and then in a separate javascript file using jquery:
.NET 4 中的默认编码器对它认为可能不安全的字符进行编码,包括 '、"、&、< 和 >。但是,此编码不应影响您尝试包含的 Javascript 代码段的执行,因为浏览器会在将 ' 传递给 Javascript 解析器之前自动将其转换回 ' 字符,如果这仍然对您的应用程序产生负面影响,请回复,以便我们考虑提交正式错误
。如果需要,您可以将 ASP.NET 使用的默认编码器更改为您自己创建的编码器 http://haacked.com/archive/2010/04/06/using-antixss-as-the-default-encoder-for- asp-net.aspx 连接 Anti-XSS 编码器所需的步骤,但如果您愿意,您可以按照相同的方式创建一个自定义 HttpEncoder,对除 ' 字符之外的所有内容进行编码。基本步骤。
The default encoder in .NET 4 encodes characters it deems to be potentially unsafe, including ', ", &, <, and >. However, this encoding should not affect the execution of the Javascript snippet you're trying to include, since the browser will automatically turn the ' back into the ' character before passing it to the Javascript parser. If this is still negatively affecting your application, please respond so that we can consider getting an official bug filed.
If you want, you can change the default encoder used by ASP.NET to one of your own creation. Phil outlined at http://haacked.com/archive/2010/04/06/using-antixss-as-the-default-encoder-for-asp-net.aspx the steps needed to hook up the Anti-XSS encoder. But if you wanted, you could make a custom HttpEncoder that encoded everything except the ' character by following the same basic steps.