Escaping JavaScript string literals in views

前端 未结 4 2141
栀梦
栀梦 2020-12-15 16:20

Is there a utility function for escaping JavaScript in ASP.NET MVC views? I often need to init a little snippet of JavaScript using some values from the view; for instance I

4条回答
  •  温柔的废话
    2020-12-15 17:00

    In my case I needed a string not a json object and this is for Asp.Net Core:

    @functions{
        public Microsoft.AspNetCore.Html.IHtmlContent ToJS(string value)
        {
            return Html.Raw("'" + value.Replace("'", "\\'").Replace("\r", "\\r").Replace("\n", "\\n") + "'");
        }
    
        public Microsoft.AspNetCore.Html.IHtmlContent ToJS(int value)
        {
            return Html.Raw("" + value);
        }
    }
    

    This will escape the ' and end of line characters. Also it leaves numbers (int) as a number. This could be overloaded to include float, decimal, etc. as needed.

    So, I don't have to think about it or do anything different for each type:

    var serverName = @ToJS(m.ServerName);
    var appSiteUrl = @ToJS(m.SiteUrl);
    var facebookId = @ToJS(m.FacebookAppId);
    

提交回复
热议问题