开发者

Escaping a double-quote in inline c# script within javascript

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.


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜