从控制器返回json

时间:2013-08-15 03:06:13

标签: jquery asp.net-mvc

如何使用json

返回多个对象
var result1 = new { stores = this.getstoreResults("param") };
var result2 = new { places = this.getplaceResults("param") };

result1和result2是具有不同属性的两个不同对象,如何组合并将它们返回到视图?

return Json(result1+result2); --How?

另外,我如何在jquery中映射它?

response($.map(data, function (item) {});

3 个答案:

答案 0 :(得分:4)

return Json(new { result1 = result1, result2 = result2 });

在js中,您可以将该属性用作var r1 = data.result1;

答案 1 :(得分:1)

实际上,您可以将响应作为一组对象返回,如:

Json(new [] { response1, response2 }) 
<{>>在侧,您可以单独转换这些对象数组。

var oCombined = {}
$.each(oJSONArray,function() 
{ 
    oCombined = $.extend(oCombined, this)
});

如果你打算在C#端做一个“JQuery扩展”版本,你可以实现这个创建一个函数,通过反映对象的所有属性进行交互并返回一个ExpandoObject动态类型(只有C#4+)作为一个组合结果,如:

function ExpandoObject Extender(object obj1, Type obj1Type, object obj2, Type obj2Type) 
{
    var result = new ExpandoObject() as IDictionary<string, object>;
    //Property Interator obj1
         result.Add(ob1.PropertyName, ..)

    //Property Interator obj2
         result.Add(ob2.PropertyName, ..)

    return result;
}

最后你的代码是:

return Json(Extender(result1,result2));

答案 2 :(得分:1)

如果两个JSON都是从相同的数据类型生成的, 将两者都添加到LIST&lt;&gt;然后使用JSON.NET(JsonConvert.DeserializeObject<T>()方法)

转换为JSON