3

I'm trying to hook into Google Analytics and have this:

@using (Html.BeginForm("Register", "Account", FormMethod.Post, 
        new { id = "account-register-form", 
        onsubmit = "_gaq.push(['_link', 'someurl'])" }))

My rendered view then looks like this:

<form action="/Account/Register/Basic" id="account-register-form" method="post" 
onsubmit="_gaq.push([&#39;_link&#39;, &#39;someurl&#39;])">

I have tried Html.Raw("_gaq.push(['_link', 'someurl'])") but this does not work, because I think BeginForm does the encoding.

3 Answers 3

2

Code works fine if don't turn off encoding but you can turn off attribute encoding by creating a class like this:

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

and adding this to web.config under :

<httpRuntime encoderType="HtmlAttributeEncodingNot"/>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks did not know about this setting. But would this be safe? I don't want to risk something by doing this.
@adriannp Safety depends on your code, there is no vulnerability for your codes on question because codes came from your source codes, but if html attributes comes from database and the supplier is web user so there is a vulnerability because you are not encoding the user supplied data. so user(hacker) can write a jscript xss or any bad codes into your html attributes. sorry for the english =) i hope you understand
1

You don't need to unencode anything. What you have is perfectly valid markup and working javascript, as seen in the following live demo:

<form action="#" method="get" onsubmit="alert(&#39;some test&#39;);">
    <input type="submit" value="OK" />
</form>

So keep your code as is.

3 Comments

I never tested it to see if it would work. Did not know this would be valid. But because this looks nasty I'm feeling dirty of having it as is ;)
@adriaanp, would you expect MVC helpers to generate invalid markup?
I guess not, I'm going to leave it as is.
1

If you don't have to use the Html.BeginForm then use can use the code snippet below to solve your formatting issue.

<form action="@Url.Action("Register", "Account")" 
    method="POST" id="account-register-form" 
    onsubmit="_gaq.push(['_link', 'someurl'])">
</form>

This outputs the html you require.

1 Comment

This is what I went with in the end, but @Darin have a point, maybe I should just left it as is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.