簡體   English   中英

asp.net mvc 3返回json數組

[英]asp.net mvc 3 return json array

嘗試在客戶端為js生成一個數組:

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

在我的asp.net mvc 3控制器中,我創建了一個entityframework模型並嘗試返回一個列表:

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

目前我無法弄清楚只是將customername + customerid屬性作為客戶列表(NWind數據庫)返回?

試試這個 - 為每個客戶創建一個具有所需屬性的新匿名對象。

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

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

請注意,如果你想要ex。 將“text”和“value”作為JSON數組中的值只需將上面的customerName和customerId更改為您想要的任何名稱。

試試這個:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM