Escaping JavaScript string literals in views

前端 未结 4 2153
栀梦
栀梦 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 16:37

    In MVC 5 using Razor templates, the following is possible:

    <script type="text/javascript">
        var page = new Page({ currentUser: @Html.Raw(Json.Encode(Model.UserName)) });
        page.init();
    </script>
    
    0 讨论(0)
  • 2020-12-15 16:38

    In .NET 4, The HttpUtility class has a variety of static encoding methods for various contexts, including a JavaScriptStringEncode method for this particular purpose.

    It's often simpler to just use JSON deserialization, though.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-15 17:01

    After some time working in ASP.NET MVC, I concluded that (most likely) there is no build-in helper for it. Of course, it's trivial to write your own. Here is it for the sake of completeness:

    using System.Web.Mvc;
    using System.Web.Script.Serialization;
    
    namespace MyProject.Helpers
    {
        public static class JsonExtensions
        {
            public static string Json(this HtmlHelper html, object obj)
            {
                JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                return jsonSerializer.Serialize(obj);
            }
        }
    }
    

    In a view, it can be used as follows:

    <script type="text/javascript">
    var page = new Page(<%= Html.Json(new { currentUser: Model.UserName } ) %>);
    page.init();
    </script>
    
    0 讨论(0)
提交回复
热议问题