开发者

asp mvc best way to return a json string from a controller

开发者 https://www.devze.com 2023-03-26 01:26 出处:网络
I have a simple Action that iterates around a dbset does a bit of manipulation on each record then returns the chosen records via json, a bit like this:

I have a simple Action that iterates around a dbset does a bit of manipulation on each record then returns the chosen records via json, a bit like this:

List<JsonResult> dataout =开发者_如何学编程 new List<JsonResult>();
foreach(var r in db.People.OrderBy("something")) {
    // do stuff to the rec
    string SubmittersName = rec.Submitter.Name;
    dataout.Add(this.Json(new { rec.Created, rec.Name, SubmittersName,  
                     OtherStuff }));
}

return new JsonResult() {
    Data = dataout.Select(r=>r),
    ContentEncoding = Encoding.UTF8,
    JsonRequestBehavior = JsonRequestBehavior.AllowGet
};

To me it seems a bit clumsy, but its easy to follow whats going on.

(Also in the returned json I get ContentEncoding:null which seems a bit strange given that I specified it)

How could this be improved on?

General sugesstions/comments appreciated.

TIA.


You're misusing JsonResult.

JsonResult isn't a way to store JSON data; it's simply a way to return JSON data from a view.
You shouldn't create a list of them.

By returning JSON from a collection of JsonResults, you're actually converting the JsonResults to JSON, including their ContentEncoding properties (which you never set).

Instead, you can directly return a collection of anonymous types:

return Json(
    db.People.OrderBy(something).Select(rec => new { rec.Created, ... }),
    JsonRequestBehavior.AllowGet
);
0

精彩评论

暂无评论...
验证码 换一张
取 消