{对不起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();
答案 0 :(得分: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。
答案 1 :(得分: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;
}