2016-02-05 104 views
0

我使用下面的ASP MVC代碼字典轉換爲JsonResult字典轉換成JSON

public JsonResult docGet() 
{ 
    ...... 

    Dictionary<string, string> dictionary = new Dictionary<string, string>(); 

    foreach (ListItem ListItem in collListItem) 
    { 
     dictionary.Add((ListItem["ID"], ListItem["Title"]);  
     } 

return Json(Result, JsonRequestBehavior.AllowGet); 
} 

此代碼不能正常工作。結果是[]。如果我將字典類型更改爲只有1個值的列表,它正在工作。但期望的結果是以json格式的鍵值對列表。

回答

0

我覺得你得到一個空的結果的主要原因是因爲你正在返回Result,不是說你填充dictionary變量。

此外,如果collListItem是IEnumerable<ListItem>(因爲它似乎是,因爲你用foreach循環它),所以你不需要逐項建立字典。

嘗試:

Dictionary<string,string> dictionary=collListItem.ToDictionary(c=>c["ID"],c=>c["Title"]); 

return Json(dictionary,JsonRequestBehavior.AllowGet);