5

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.

3 Answers 3

9

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, I don't have .NET 4. What does it do?
It escapes a bunch of characters. Use WPL.
2

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'")

Comments

0

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
};

3 Comments

That's very wrong. You should not be replacing \r with <br /> tags, and there are more characters that you need to escape.
Specifically: backslash itself (otherwise \" is escaped to \\" and breaks the string with security implications) and other newline characters.
This is what works for me, and the messages I need to encode. Feel free to adjust to your individual needs

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.