Skanda
Skanda

Reputation: 131

A method in controller to return two json objects

Public JsonResult GetDetails()
{ 
  List<Cust> Customers = new List<Cust>();
  Customers = GetCustomerDetails();
  var name = Customers.Select(e => new{e.custname}).Distinct().ToList();
  var dept =  Customers.Select(e => new{e.deptname}).Distinct().ToList();
  var response = new{CustomerNames = name, CustomerDepartments = dept};
  return Json(response, JsonRequestBehaviour.AllowGet();
}

I have this above method returning a json object, now this method has to return a subset of this response along with the one its returning, is it possible to do a filter on department type and return two jon objects from same method.

Upvotes: 0

Views: 834

Answers (1)

Shyju
Shyju

Reputation: 218922

Sure. You can add one more property to your anonymous object and return that.

public JsonResult GetDetails()
{ 
  var customers = GetCustomerDetails();
  var names = customers.Select(e => new {e.custname}).Distinct().ToList();
  var depts =  customers.Select(e => new { e.deptname}).Distinct().ToList();
  var deptSubSet = depts.Where(f=>f.deptname=="IT").ToList(); 
  //replace this with your condition

  var response = new {  CustomerNames = names, 
                        CustomerDepartments = depts,
                        FilteredDepartments = deptSubSet 
                     };
   return Json(response, JsonRequestBehaviour.AllowGet();
}

Replace the Where condition linq code with whatever where clause you need to use to get the sub set.

BTW, The result is not going to be an array, It will be an object with 3 properties. The value of those properties will be an array.

Upvotes: 2

Related Questions