Asp.net mvc 3 return json array

Trying to create a client side array for js:

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

In my asp.net mvc 3 controller, I created an entityframework model and tried to return a list:

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

at the moment I can’t figure out how to return the customername + customerid property to the customer list (NWind database)?

+4
source share
2 answers

Try this - for each client, 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 like, for example. "text" and "value" should be the values ​​in your JSON array, just change the client name and customerId above to whatever names you want.

+8
source

try the following:

 public ActionResult GetCustomers() { var customers = for c in db.Customers select new { text = c.CustomerName, value = c.CustomerId}; return Json( customers.ToArray(), JsonRequestBehavior.AllowGet); } 
+5
source

Source: https://habr.com/ru/post/1501383/


All Articles