从集合IEnumerable中仅将少数属性返回给JSON Result的最佳方法是什么?
Department对象有7个属性我只需要在客户端中有2个属性。我可以使用C#匿名类型吗?
public class Department
{
public string DeptId { get; set; }
public string DeptName { get; set; }
public string DeptLoc1 { get; set; }
public string DeptLoc2 { get; set; }
public string DeptMgr { get; set; }
public string DeptEmp { get; set; }
public string DeptEmp2 { get; set; }
}
[HttpGet]
public JsonResult DepartmentSearch(string query)
{
IEnumerable<Department> depts = DeptSearchService.GetDepartments(query);
//Department object has 15 properties, I ONLY need 2 (DeptID and DeptName) in the view via returns JSON result)
return Json(depts, JsonRequestBehavior.AllowGet); // I don’t want all the properties of a department object
}
答案 0 :(得分:0)
当然,我json一直在序列化匿名类型。是一个明智的计划。
答案 1 :(得分:0)
使用Linq投影
未经测试的代码
var deptsProjected = from d in depts
select new {
d.DeptId,
d.DeptName
};
return Json(deptsProjected , JsonRequestBehavior.AllowGet);
答案 2 :(得分:0)
var deptnames = depts.Select(d => new { d.DeptID, d.DeptName });
然后使用deptnames