2013-10-21 102 views
0

的JSON输出这是我的模型:价值属性

public class Model { 

    (...) 

    [Required] 
    [Display(Name = "Created By")] 
    public UserProfile CreatedBy { get; set; } 
    [Display(Name = "Changed By")] 
    public UserProfile ChangedBy { get; set; } 

} 

我希望输出这些字段是用户配置类中的用户名属性。现在,做一个简单的JSON输出时,它只是输出

CreatedBy: null 
ChangedBy null 

(我试图覆盖在用户配置类的ToString()方法返回的用户名,但没有帮助。)

我怎么能使它在使用json输出时,我可以获得用户名字段值?

这是我如何JSON输出数据:

public class MyController : ApiController 
{ 

    public List<Model> Get(string param1, string param2) 
    { 

     DbContext db = new DbContext(); 

     List<Model> list = (from d in db.Models 
           select d 
           ).ToList(); 


     return list; 

    } 
} 
+1

默认的Json串行器已经为你做了这个。当您从数据库中获取时,看起来您并未包含此字段。你应该发布更多的代码! – Fals

+0

我将ApiController的代码添加到了我原来的帖子中。让我知道你还需要我展示什么。 – fobia

+0

仍在苦苦挣扎着..不知道如何显示UserProfile类的Username属性... – fobia

回答

0

首先,你必须返回的ActionResult/JsonResult得到的Json出来。

public ActionResult GetJson() 
{ 
    var result=from m in db.Models select new { CreatedBy=m.CreatedBy.Name, ChangedBy=m.ChnangedBy.Name }; 
    return Json(result, JsonRequestBehaviour.AllowGet) 
}