从 mvc 4 中的控制器,我使用实体框架从数据库中的模型请求对象集合:
    [HttpPost]
    public ActionResult RequestDbObjects()
    {
        List<MyObjectType> objCollection;
        using (DataContext context = new DataContext())
        {
            objCollection= context.MyObjects.Where(o => o.TypeId == 1).OrderBy(k => k.Name).ToList();
        }
        return Json(objCollection);
    }
模型:
[Table("MyObjects")]
public class MyObjectType
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Description { get; set; }
    [Required]
    [ForeignKey("Type")]
    public int TypeId { get; set; }
    public virtual Type Type{ get; set; }
}
[Table("Type")]
public class Type
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
}
在视图中,使用脚本:
   function recollectData() {         
       $.ajax({
           url: "/Controller/RequestDbObjects/",
           type: 'POST',
           success: function (dataCollection) {
              for(var obj in dataCollection)
              {
                 var value = dataCollection[obj];
              }
           },
           error: function () {
               alert('Cannot retrieve the data');              
           }
       });             
   };
在上面的控制器中,首先我调用控制器中的操作,该操作使用实体框架从数据库请求数据,然后从返回到脚本的对象列表中,我想迭代它们,并为它们中的每一个读取一些属性和做一些东西,但我不知道怎么做。想法?