Please help!! C# Anonymous and returning filtered properties with JSON
- by Raj Aththanayake
What is the best way to return only few properties to JSON Result from a collection IEnumerable?
Department object has 7properties I only need to 2 of them in client. Can I do this using C# anonymous types?
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
}