在视图中转义JavaScript字符串文字 [英] Escaping JavaScript string literals in views

查看:77
本文介绍了在视图中转义JavaScript字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在用于在ASP.NET MVC视图中转义JavaScript的实用程序功能?我经常需要使用视图中的一些值来初始化一小段JavaScript.例如,我可能有类似的东西:

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 may have something like:

<script type="text/javascript">
var page = new Page({ currentUser: "<%= Model.UserName %>" });
page.init();
</script>

我希望这样:

<script type="text/javascript">
var page = new Page({ currentUser: "<%= Html.JavaScriptEscape(Model.UserName) %>" });
page.init();
</script>

我当然可以自己编写函数.但是,由于已经有内置的实用程序以HTML编码的形式出现,并且由于ASP.NET MVC的卖点之一是<%%>是默认的呈现模式,而且由于我要实现的目标是常见的问题,这让我感到奇怪,为什么我找不到已经内置的东西.例如,是否存在一种简单而优雅的方法将视图中的对象序列化为JSON?

I could, of course, write the function myself. But since there are already built-in utilities form HTML encoding, and since one of the selling points of ASP.NET MVC is that the <% %> is the default rendering mode, and since what I'm trying to achieve is quite common, it makes me wonder why I cannot find anything like that already built-in. Is there, for instance, an easy and elegant way to serialize an object to JSON in views?

还是正在做一些违反ASP.NET MVC原则的事情?当我遇到这样的问题时,通常会认为我做错了什么,因为我认为框架设计人员花了一些时间在现实世界中思考问题.

Or am doing something against ASP.NET MVC principles? When I hit a problem like this, it usually makes it think that either I’m doing something wrong since I assume that the framework designers spent some time thinking about real world scenarios.

推荐答案

在ASP.NET MVC中工作了一段时间后,我得出结论:(很可能)没有内置帮助器.当然,编写自己的代码很简单.为了完整起见,这里是它:

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>

这篇关于在视图中转义JavaScript字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆