javascript asp.net mvc 3 返回 json 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18708708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
asp.net mvc 3 return json array
提问by user603007
Trying to generate an array on the client side for js:
尝试在客户端为 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 :
在我的 asp.net mvc 3 控制器中,我创建了一个实体框架模型并尝试返回一个列表:
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)?
目前我无法弄清楚只是将 customername+customerid 属性作为客户列表返回(NWind 数据库)?
回答by Adam Tuliper - MSFT
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.
请注意,如果您想要为前。"text" 和 "value" 作为 JSON 数组中的值,只需将上面的 customerName 和 customerId 更改为您想要的任何名称。
回答by Roger Barreto
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);
}