从MVC控制器返回JSON数据 [英] Returning Json data from MVC controller

查看:327
本文介绍了从MVC控制器返回JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 公众的ActionResult关于()
    {
        清单<存储> listStores =新的List<存储>();
        listStores = this.GetResults(参数);
        返回JSON(listStores,存储,JsonRequestBehavior.AllowGet);
    }

使用上述code,我能得到下面的结果

<$p$p><$c$c>[{\"id\":\"1\",\"name\":\"Store1\",\"cust_name\":\"custname1\",\"telephone\":\"1233455555\",\"email\":\"abc@ac.com\",\"geo\":{\"latitude\":\"12.9876\",\"longitude\":\"122.376237\"}},{\"id\":\"2\",\"name\":\"Store2\",\"cust_name\":\"custname2\",\"telephone\":\"1556454\",\"email\":\"nfnf@ac.com\",\"geo\":{\"latitude\":\"12.9876\",\"longitude\":\"122.376237\"}},

如何将我能够得到的结果在下面的格式?

  {专卖店:[
{编码:1,名称:商店1,CUST_NAME:custname1,电话:1233455555,电子邮件:abc@ac.com,
地缘:{纬度:12.9876,东经:122.376237}},{\"id\":\"2\",\"name\":\"Store2\",\"cust_name\":\"custname2\",\"telephone\":\"1556454\",\"email\":\"nfnf@ac.com\",\"geo\":{\"latitude\":\"12.9876\",\"longitude\":\"122.376237\"}} ]
}

我想有商店在数据的开始。

请帮我在这方面。


解决方案

您需要创建一个包含属性命名卖场内的店面的对象:

 公众的ActionResult关于()
{
    VAR的结果= {新门店= this.GetResults(参数)};
    返回JSON(因此,存储,JsonRequestBehavior.AllowGet);
}

我在这里使用匿名类型为简单起见,如果这个结果类型是在你可以考虑为它创造一个合适的类多处必需的。

   public ActionResult About()
    {
        List<Stores> listStores = new List<Stores>();
        listStores = this.GetResults("param");
        return Json(listStores, "Stores", JsonRequestBehavior.AllowGet);
    }

Using the above code I am able to get the below result

[{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555","email":"abc@ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}},

{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454","email":"nfnf@ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}},

How would I able to get the result in below format?

{

"stores" : [
{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555","email":"abc@ac.com",
"geo":{"latitude":"12.9876","longitude":"122.376237"}},

{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454","email":"nfnf@ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}} ] 
}

I would like to have the stores at the beginning of the data.

Please help me in this regard.

解决方案

You will need to create an object that contains the stores within a property named stores:

public ActionResult About()
{
    var result = new { stores = this.GetResults("param") };
    return Json(result, "Stores", JsonRequestBehavior.AllowGet);
}

I've used an anonymous type for simplicity here, if this result type were required in multiple places you may consider creating a 'proper' class for it.

这篇关于从MVC控制器返回JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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