5

{Sorry new to JSON} I need to build up an array of resources (Users) and pass it in to my view, might be a better way than what ive done below? (Demo)

My model is simply

public class ScheduleUsers
    {
        public string Resource{ get; set; }
}

On my controller

var users = new JsonArray(
               new JsonObject(
                new KeyValuePair<string,JsonValue>("id","1"),
                new KeyValuePair<string,JsonValue>("name","User1")),
                new JsonObject(
                new KeyValuePair<string, JsonValue>("id", "2"),
                new KeyValuePair<string, JsonValue>("name", "User2"))
                  );
            model.Resources = users.ToString();
1
  • 1
    I like anonymous types for quick projection, e.g. return Json( new { foo = "bar" } ). Json.NET is also quite popular and gives you numerous options.
    – Tim M.
    May 31, 2013 at 6:22

2 Answers 2

14

Why don't you just return a list of entities as a JSON result, like:

public class CarsController : Controller  
{  
    public JsonResult GetCars()  
    {  
        List<Car> cars = new List<Car>();
        // add cars to the cars collection 
        return this.Json(cars, JsonRequestBehavior.AllowGet);  
    }  
} 

It will be converted to JSON automatically.

2
  • Ok so i did that, and changed model.Resources = GetResources().ToString(); but when looking at the html output i get resources:System.Web.Mvc.JsonResult
    – D-W
    May 31, 2013 at 8:33
  • 2
    add return this.Json(cars,JsonRequestBehavior.AllowGet ); otherwise you get this error
    – Shaiju T
    Feb 1, 2016 at 16:02
3

I did this and this works

    JavaScriptSerializer js = new JavaScriptSerializer();
                StringBuilder sb = new StringBuilder();
                //Serialize  
                js.Serialize(GetResources(), sb);



 public List<ScheduledResource> GetResources()
        {
            var res = new List<ScheduledResource>()
                {
                    new ScheduledResource()
                        {
                            id = "1",
                            color = "blue",
                            name = "User 1"
                        },
                    new ScheduledResource()
                        {
                            id = "2",
                            color = "black",
                            name = "User 2"
                        },

                };

            return res;
        }

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.