2013-05-31 24 views
5

{对JSON}新的我需要建立一个资源(用户)数组,并将其传递到我的看法,可能是比什么是更好的方式下面做? (演示)更优雅的方式返回json数组到ASP.NET MVC

我的模型只是

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(); 
+1

我喜欢匿名类型快速投影,如'返回Json(new {foo =“bar”})''。 [Json.NET](http://james.newtonking.com/pages/json-net.aspx)也很受欢迎,并给你许多选择。 –

回答

13

你为什么不只是返回实体的列表作为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。

+0

好吧,我这样做了,并改变了model.Resources = GetResources()。ToString();但当我看到html输出时,我得到的资源:System.Web.Mvc.JsonResult –

+0

你最好显示你的新代码... –

+2

** add **'return this.Json(cars,JsonRequestBehavior.AllowGet);'否则你得到[这](http://stackoverflow.com/questions/5588143/ef-4-1-code-first-json-circular-reference-serialization-error)错误 – stom

2

我这样做,这一点也适用

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; 
     } 
相关问题