I need to escape a double quote in inline c# within javascript. Code is below:
if (\"<%= TempData[\"Message\"]%>\" == \"\") {
// code
};
You can use the AjaxHelper.JavaScriptStringEncode method inside a Razor view, like this:
if ("@Ajax.JavaScriptStringEncode(TempData["Message"].ToString())" == "") {
// do stuff
}
If that's too verbose, create this little helper in /App_Code/JS.cshtml
@helper Encode(string value) {
@(HttpUtility.JavaScriptStringEncode(value))
}
Which you can then call from any view:
@JS.Encode("'single these quotes are encoded'")
Call HttpUtility.JavaScriptStringEncode.
This method is new to ASP.Net 4.0; for earlier versions, use the WPL.
I have addressed this by writing a HtmlHelper that encodes the strings to a format acceptable in Javascript:
public static string JSEncode(this HtmlHelper htmlHelper, string source)
{
return (source ?? "").Replace(@"'", @"\'").Replace(@"""", @"\""").Replace(@"&", @"\&").Replace(((char)10).ToString(), "<br />");
}
Then, in your view:
if ('<%= Html.JSEncode( TempData["Message"] ) %>' == "") {
// code
};