Stop the tag builder escaping single quotes ASP.NET MVC 2

后端 未结 4 1501
一生所求
一生所求 2020-12-10 02:59

I have the following HtmlHelper method that I want to create a button that does a redirect with JavaScript:

public static string JavaScriptButto         


        
4条回答
  •  盖世英雄少女心
    2020-12-10 03:17

    While the solution provided by Ryan may work, it is a little like using a hammer to swat a fly.

    The issue is that TagBuilder encodes strings during calls to MergeAttributes(). For the required Javascript in a button link this affects single quotes and spaces.

    The last step of the required extension method is the return of an MvcHtmlString (which receives no further encoding), so it is perfectly reasonable to make some simple text corrections to the string (to undo the encoding) before creating that object.

    e.g.

    return new MvcHtmlString(tb.ToString(TagRenderMode.Normal).Replace("'", "\'").Replace(" "," "));
    

    A complete ActionLinkButton helper is shown below:

    public static class ActionLinkButtonHelper
    {
        public static MvcHtmlString ActionLinkButton(this HtmlHelper htmlHelper, string buttonText, string actionName, object routeValuesObject = null, object htmlAttributes = null)
        {
            return ActionLinkButton(htmlHelper, buttonText, actionName, "", routeValuesObject, htmlAttributes);
        }
        public static MvcHtmlString ActionLinkButton(this HtmlHelper htmlHelper, string buttonText, string actionName, string controllerName, object routeValuesObject = null, object htmlAttributes = null)
        {
            if (string.IsNullOrEmpty(controllerName))
            {
                controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
            }
            RouteValueDictionary routeValues = new RouteValueDictionary(routeValuesObject);
            RouteValueDictionary htmlAttr = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
            TagBuilder tb = new TagBuilder("button");
            tb.MergeAttributes(htmlAttr, false);
            string href = UrlHelper.GenerateUrl("default", actionName, controllerName, routeValues, RouteTable.Routes, htmlHelper.ViewContext.RequestContext, false);
    
            tb.MergeAttribute("type", "button");
            tb.SetInnerText(buttonText);
            tb.MergeAttribute("value", buttonText);
            tb.MergeAttribute("onclick", "location.href=\'"+ href +"\';return false;");
            return new MvcHtmlString(tb.ToString(TagRenderMode.Normal).Replace("'", "\'").Replace(" "," "));
        }
    }
    

    This does everything you need to add button links, has the most useful overloads you use with ActionLink and does not potentially cause unexpected application-wide changes by changing the attribute encoding process.

提交回复
热议问题