0

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.

gideon
19.5k11 gold badges74 silver badges114 bronze badges
asked Aug 4, 2011 at 13:26

1 Answer 1

0

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
);
answered Aug 4, 2011 at 13:28

3 Comments

You can put that in the Select call, or add them to a List<object>. (Since you cannot easily declare a list of anonymous types)
exactly the problem not easliy anyway. ArrayList works which is the way i think i'll go to get rid of the problem. I have tried to put the tranform function into the select but it proved difficult, I kept getting lots of compiler errors about not be able to parse the anon function into an expression tree.
Oh; you're using LINQ to SQL. You can fix those errors by calling AsEnumerable() before Select().

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.