views:

31

answers:

1

Hi,

I have the following HtmlHelper method that I want to create a button that does a redirect with 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();         
}

The problem is that the line that creates the onclick handler is getting escaped by the tagbuilder, the resulting html is:

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

Is there anyway I can stop this behaviour?

Cheers

Paul

A: 

This is actually an issue with .NET 4.0. To fix it you need to override the attribute encoding process.

public class HtmlAttributeNoEncoding : System.Web.Util.HttpEncoder
{
    protected override void HtmlAttributeEncode(string value, System.IO.TextWriter output)
    {
        output.Write(value);
    }
}

Then put this in your web.config file under the <system.web> element:

<httpRuntime encoderType="HtmlAttributeNoEncoding"/>

I found this here.

Ryan