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.JsonResultisn’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 theJsonResults to JSON, including theirContentEncodingproperties (which you never set).Instead, you can directly return a collection of anonymous types: