Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More Elegant way to return json array to ASP.NET MVC

{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();
like image 406
D-W Avatar asked May 31 '13 06:05

D-W


2 Answers

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.

like image 176
L-Four Avatar answered Nov 01 '22 11:11

L-Four


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;
        }
like image 3
D-W Avatar answered Nov 01 '22 11:11

D-W