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

后端 未结 3 1728
轮回少年
轮回少年 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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(), "
    "); }

    Then, in your view:

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

提交回复
热议问题