从 MVC 控制器返回 Json 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9326754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:11:35  来源:igfitidea点击:

Returning Json data from MVC controller

asp.net-mvcjson

提问by user557211

   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":"[email protected]","geo":{"latitude":"12.9876","longitude":"122.376237"}},

{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454","email":"[email protected]","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":"[email protected]",
"geo":{"latitude":"12.9876","longitude":"122.376237"}},

{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454","email":"[email protected]","geo":{"latitude":"12.9876","longitude":"122.376237"}} ] 
}

I would like to have the storesat the beginning of the data.

我想stores在数据的开头。

Please help me in this regard.

请在这方面帮助我。

回答by Rich O'Kelly

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

您将需要创建一个对象,该对象包含名为 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.

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

回答by Tx3

JavaScriptSerializercan be found from namespace System.Web.Script.Serialization

JavaScriptSerializer可以从命名空间中找到 System.Web.Script.Serialization

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

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

回答by Karan Singh

if you want to send object to client side as Json format like Data-table,List,Dictionary etc. then need to override jsonResult and ExecuteResult

如果您想将对象以 Json 格式(如 Data-table、List、Dictionary 等)发送到客户端,则需要覆盖 jsonResult 和 ExecuteResult

other wise use linq format to return data like

其他明智的使用 linq 格式返回数据,如

using JSON.NET(must need to use override jsonResult and ExecuteResult )

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

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


other option using linq

使用 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);

override methods

覆盖方法

 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;
                }
            }
        }

回答by Tr1stan

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);
}