5

{Sorry new to JSON} 我需要建立一个资源数组(用户)并将其传递给我的视图,这可能比我在下面所做的更好吗?(演示)

我的模型很简单

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

在我的控制器上

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();
4

2 回答 2

14

为什么不直接返回一个实体列表作为 JSON 结果,例如:

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);  
    }  
} 

它将自动转换为 JSON。

于 2013-05-31T06:24:01.527 回答
3

我这样做了,这行得通

    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;
        }
于 2013-05-31T09:26:41.247 回答