从ASP.NET MVC返回包含javascript函数的JSON

时间:2012-06-20 11:07:26

标签: asp.net-mvc json

我有一个类似JSON的数据结构(我不想改变),当前由.aspx文件吐出javascript生成。看起来.NET在午餐时吃了jQuery,然后呕吐......

我想将整个事情重写为返回JsonResult的MVC控制器操作,基本上是通过构建匿名对象并将其传递给return Json(data)

但是,当我想构建的JSON对象的某些属性实际上是JavaScript函数时,我无法弄清楚如何构造C#对象。我该怎么做?

示例:

我想创建以下类似JSON的对象:

{
    id: 55, 
    name: 'john smith', 
    age: 32,
    dostuff: aPredefinedFunctionHandle,
    isOlderThan: function(other) { return age > other.age } 
}

您看到我希望能够为我在其他地方定义的JavaScript函数指定两个函数句柄(通常在.js文件中),并且我想要定义新的内联函数。

我知道如何在C#中构建该对象的一部分:

var data = new { id = 55, name = "john smith", age = 32 };
return Json(data);

还有其他方法吗?

3 个答案:

答案 0 :(得分:2)

.NET中没有内置类型映射到javascript函数。因此,您可能必须创建一个代表函数的自定义类型,并且您必须自己进行序列化。

像这样......

public class JsFunction
{
   public string FunctionString{get; set;}
}

new
{
    id = 55, 
    name = 'john smith', 
    age = 32,
    dostuff = new JsFunction{ FunctionString = "aPredefinedFunctionHandle" },
    isOlderThan = new JsFunction{ FunctionString = "function(other) { return age > 
                    other.age" } 
}

在序列化时,您可能必须检查值的类型,并将FunctionString直接写入响应,而不使用双引号。

答案 1 :(得分:0)

JSON显式排除函数,因为它不是一个仅限JavaScript的数据结构(尽管名称中包含JS)。所以我们不应该在JSON中包含函数名称

答案 2 :(得分:0)

JSON排除了函数。听起来你想要将数据封装到一个类中。如下所示:

function Person(data) {
   this.id = data.id;
   this.name = data.name;
   this.age = data.age;
   this.isOlderThan = function(other) { return this.age > other.age };

}