0

这是我的模型:

public class Model {

    (...)

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

}

我希望这些字段的输出是 UserProfile 类中的 Username 属性。现在,当做一个简单的 JSON 输出时,它只是输出

CreatedBy: null
ChangedBy null

(我尝试覆盖 UserProfile 类上的 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;

    }
}
4

1 回答 1

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)
}
于 2013-10-23T16:16:23.280 回答