2012-05-09 72 views
0

看起来这应该很容易,但我似乎无法弄清楚如何访问我的键/值对:如何处理客户端的字典?

在服务器端:

public JsonResult GetDict(int type) 
    { 
    Repository repo = new Repository(); 
    Dictionary<int,string> dict = repo.getDict(type); 
    return Json(dict, JsonRequestBehavior.AllowGet); 
    } 

一个客户端:

var mySelect = $('#mySelect'); 
    mySelect .empty(); 
    mySelect .append($('<option/>', { value: "", text: "-- pick one --" })); 

    $.getJSON("/controller/GetDict/", { type: 1 }, function (dict, status) { 
    // this doesn't work 
    $.each(dict, function (index, entry) { 
     mySelect .append($('<option/>', { 
      value: entry.Key, 
      text: entry.Value 
     })); 
    }); 
    }); 

如何从我的getJSON调用返回的字典中创建我的选择列表?

事实证明我的getJSON调用抛出一个错误:

类型“System.Collections.Generic.Dictionary”的字典的序列化/反序列化不支持,钥匙必须是字符串或对象。

如何返回键/值对,其中的键是int?我是否需要创建自己的包装类?

回答

0

当传递到字典然后$.eachindex一个键和entry一个值,即

$.each(dict, function (key, value) { 
    var opt = $('<option>', { value:key, text: value }); 
    mySelect.append(opt); 
});