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 JsonResult
s, you're actually converting the JsonResult
s 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
);
精彩评论