加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 00:27:44 所属栏目:asp.Net 来源:网络整理
导读:我有以下HtmlHelper方法,我想创建一个使用JavaScript重定向的按钮: public static string JavaScriptButton(this HtmlHelper helper,string value,string action,string controller,object routeValues = null,object htmlAttributes = null){ var a = (ne
我有以下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。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读