If you need to put valid JavaScript or a URL in to a .NET button's onclick attribute, for example, security scanning software might flag any untrusted data and ask you to encode the value, but you'll end up with invalid JS and/or URL's.
e.g.
This would work, but get flagged by the security scan:
someButton.Attributes["onclick"] = "document.location.href = '" + someUrl + "'; return false;";
This would be a mess of escape chars in the browser:
someButton.Attributes["onclick"] = Microsoft.Security.Application.Encoder.HtmlAttributeEncode("document.location.href = '" + someUrl + "'; return false;");
So would this:
var encodedUrl = Microsoft.Security.Application.Encoder.UrlEncode(someUrl);
var encodedJs = Microsoft.Security.Application.Encoder.JavaScriptEncode(string.Format("document.location.href = '{0}'; return false;", endocdedUrl);
someButton.Attributes["onclick"] = encodedJs;
Based on this thread, I also tried using Page.ClientScript.RegisterStartupScript, but again, anything I send to the browser that has been encoded is invalid.
I suppose I could decode on the client but surely that negates the whole encoding exercise? I must be missing something obvious here?