从MVC控制器返回Json数据

时间:2012-02-17 10:41:16

标签: asp.net-mvc json

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

使用上面的代码我可以得到以下结果

[{"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"}},

我如何以下面的格式获得结果?

{

"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"}} ] 
}

我希望在数据开头有stores

请帮助我。

4 个答案:

答案 0 :(得分:5)

您需要创建一个对象,该对象包含名为stores的属性中的商店:

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

我在这里使用匿名类型来简化,如果在多个地方需要这种结果类型,你可以考虑为它创建一个“适当的”类。

答案 1 :(得分:1)

JavaScriptSerializer可以在命名空间System.Web.Script.Serialization

中找到
var ser = new JavaScriptSerializer();
var jsonStores = ser.Serialize(stores);

return Json(new { stores: jsonStores }, "Stores", JsonRequestBehavior.AllowGet);

答案 2 :(得分:1)

如果要将对象作为Json格式发送到客户端 比如Data-table,List,Dictionary等,然后需要覆盖jsonResult和ExecuteResult

另外明智地使用linq格式来返回数据 喜欢

使用JSON.NET(必须使用覆盖jsonResult和ExecuteResult)

  DataTable dt = new DataTable();//some data in table
   return json("data",JsonConvert.SerializeObject(dt))

使用linq的其他选项

var Qry = (from d in dt.AsEnumerable()
                               select new
                               {
                                   value = d.Field<int>("appSearchID"),
                                   text = d.Field<string>("appSaveSearchName"),
                                   type = d.Field<int>("appSearchTypeStatus")
                               });
                     return json("Data", Qry);

覆盖方法

 protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            try
            {
                    return new JsonNetResult
                    {
                        Data = data,
                        ContentType = contentType,
                        ContentEncoding = contentEncoding,
                        JsonRequestBehavior = behavior,
                        MaxJsonLength = int.MaxValue
                    };

            }
            catch (Exception)
            {
                throw;
            }
        }

    public class JsonNetResult : JsonResult
        {
           public override void ExecuteResult(ControllerContext context)
            {
                try
                {
                HttpResponseBase response = context.HttpContext.Response;
                    response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
                    if (this.ContentEncoding != null)
                        response.ContentEncoding = this.ContentEncoding;
                    if (this.Data == null)
                        return;
                    using (StringWriter sw = new StringWriter())
                    {
                        response.Write(this.Data);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

答案 3 :(得分:-1)

public class StoresViewModel{
    public List<Stores> stores {get;set;}
}


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