2010-05-19 4 views
4

Quel est le meilleur moyen de renvoyer seulement quelques propriétés à JSON Résultat d'une collection IEnumerable?C# Propriétés filtrées anonymes et renvoyées avec JSON

L'objet de département a 7propriétés J'ai seulement besoin de 2 d'entre eux dans client. Puis-je le faire en utilisant des types anonymes 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 
    } 

Répondre

0
var deptnames = depts.Select(d => new { d.DeptID, d.DeptName }); 

Ensuite, il suffit d'utiliser deptnames

0

Bien sûr, je json sérialiser les types anonymes tout le temps. Est-ce un plan raisonnable.

0

Utilisez projection Linq

code non testé

var deptsProjected = from d in depts 
        select new { 
         d.DeptId, 
         d.DeptName 
        }; 
return Json(deptsProjected , JsonRequestBehavior.AllowGet); 
+0

me semble bon. –

Questions connexes