asp.net mvc 3 return json array

15,923

Solution 1

Try this - for each customer create a new anonymous object with the properties you want.

public ActionResult GetCustomers()
{ 
    var customers = from o in db.Customers
                select new { customerName = o.CustomerName, customerId = o.CustomerId};

    return Json(customers.ToList(), JsonRequestBehavior.AllowGet);
}

Note if you want for ex. "text" and "value" to be the values in your JSON array simply change customerName and customerId above to whatever names you want.

Solution 2

try this:

public ActionResult GetCustomers()
{ 
     var customers = for c in db.Customers
            select new { text = c.CustomerName, value = c.CustomerId};

     return Json( customers.ToArray(), JsonRequestBehavior.AllowGet);
}
Share:
15,923
user603007
Author by

user603007

Updated on June 22, 2022

Comments

  • user603007
    user603007 about 2 years

    Trying to generate an array on the client side for js:

    var ds = [{ text: "john", value: "1" }, { text: "paul", value: "2" }];
    

    In my asp.net mvc 3 controller I have created a entityframework model and trying to return a list :

    NORTHWNDEntities db = new NORTHWNDEntities();
    public ActionResult GetCustomers()
    { 
        return Json( db.Customers,JsonRequestBehavior.AllowGet);
    }
    

    at the moment I cant figure out just to return the customername+customerid property as a list of customers (NWind database)?

  • Mwas
    Mwas over 6 years
    How could I include a where clause in that query?