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

馋奶兔 提交于 2019-11-29 11:04:50

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
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!