【问题标题】:asp.net mvc 3 return json arrayasp.net mvc 3 返回 json 数组
【发布时间】:2013-09-09 23:43:19
【问题描述】:

尝试在客户端为js生成一个数组:

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

在我的 asp.net mvc 3 控制器中,我创建了一个实体框架模型并尝试返回一个列表:

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

目前我无法弄清楚只是将 customername+customerid 属性作为客户列表(NWind 数据库)返回?

【问题讨论】:

    标签: javascript jquery asp.net-mvc-3 c#-4.0


    【解决方案1】:

    试试这个 - 为每个客户创建一个具有您想要的属性的新匿名对象。

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

    如果你想要前,请注意。 "text" 和 "value" 作为 JSON 数组中的值,只需将上面的 customerName 和 customerId 更改为您想要的任何名称。

    【讨论】:

    • 我如何在该查询中包含where 子句?
    【解决方案2】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2011-12-30
      • 1970-01-01
      • 2013-05-26
      • 2011-08-03
      • 1970-01-01
      • 2014-03-30
      • 2010-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多