微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

停止代码构建器转义单引号ASP.NET MVC 2

我有以下HtmlHelper方法,我想创建一个使用JavaScript重定向的按钮:
public static string JavaScriptButton(this HtmlHelper helper,string value,string action,string controller,object routeValues = null,object htmlAttributes = null)
{
    var a = (new UrlHelper(helper.ViewContext.RequestContext))
                            .Action(action,controller,routeValues);

    var builder = new TagBuilder("input");
    builder.Attributes.Add("type","submit");
    builder.Attributes.Add("value",value);
    builder.Attributes.Add("class","button");
    builder.Attributes.Add("onclick",string.Format("javascript:location.href='{0}'",a));
    builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

    return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing)).ToString();         
}

问题是创建onclick处理程序的行正在被tagbuilder转义,结果是html是:

<input class="button" onclick="javascript:location.href=&#39;&#39;" type="submit" value="Return to All Audits" />

有没有办法停止这种行为?

解决方法

这实际上是.NET 4.0的一个问题。要修复它,您需要覆盖属性编码过程。
public class HtmlAttributeNoEncoding : System.Web.Util.HttpEncoder
{
    protected override void HtmlAttributeEncode(string value,System.IO.TextWriter output)
    {
        output.Write(value);
    }
}

然后将其放在您的web.config文件的< system.web>元件:

<httpRuntime encoderType="HtmlAttributeNoEncoding"/>

我发现这个here

原文地址:https://www.jb51.cc/aspnet/252329.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐