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

后端 未结 3 1706
轮回少年
轮回少年 2020-12-19 13:28

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

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

相关标签:
3条回答
  • 2020-12-19 14:06

    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'")
    
    0 讨论(0)
  • 2020-12-19 14:14

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

    0 讨论(0)
  • 2020-12-19 14:26

    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 讨论(0)
提交回复
热议问题