views:

140

answers:

2

I need to escape a double quote in inline c# within javascript. Code is below:

if ("<%= TempData["Message"]%>" == "") {
    // code
};

Normally, I would just use single quotes like so:

if ('<%= TempData["Message"]%>' == "") {
    // code
};

However, TempData["Message"] has single quotes within it (when it contains a link generated by the Html.ActionLink() helper in ASP.NET MVC). So while I could change all the ActionLink helpers inside TempData["Message"] to tags, it's an interesting problem and would been keen to hear if anyone has an answer.

+2  A: 

Call HttpUtility.JavaScriptStringEncode.
This method is new to ASP.Net 4.0; for earlier versions, use the WPL.

SLaks
Hmm, I don't have .NET 4. What does it do?
ajbeaven
It escapes a bunch of characters. Use WPL.
SLaks
Ajax.JavaScriptStringEncode seemed to work. Any comment?
ajbeaven
I was unaware of it. It should work fine.
SLaks
Great, thanks :) +1
ajbeaven
A: 

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
};
Clicktricity
That's very wrong. You should not be replacing `\r` with `<br />` tags, and there are more characters that you need to escape.
SLaks
Specifically: backslash itself (otherwise `\"` is escaped to `\\"` and breaks the string with security implications) and other newline characters.
bobince
This is what works for me, and the messages I need to encode. Feel free to adjust to your individual needs
Clicktricity
Your code is an XSS hole. You should fix it.
SLaks