2014-02-19 113 views
2

我想讓WebApi控制器爲下拉框返回一個Dictionary(鍵值對)。這是使用angularjs $ http.get()方法。當我將數據返回到我的控制器並檢查javascript時,看起來我得到的對象的屬性在Dictionary中與我的鍵名稱相同。這不起作用,下拉列表保持空白。WebAPI返回選擇框的KeyValue列表

JavaScript的結果從$ http.get()

Object 
test1: "test 1" 
test2: "test 2" 

的WebAPI代碼:

[HttpGet] 
public Dictionary<string, string> Get() 
{ 
    return new Dictionary<string, string>(){ 
     { "test1", "test 1"}, 
     { "test2", "test 2"} 
    }; 

代碼在我看來:

<select name="originType" class="form-control" 
     ng-model="OriginType" 
     ng-options="type.Key as type.Value for type in values"> 
</select> 

而且我的控制器:

$http.get('/api/mycontroller'); 
     .success(function (values) { 
      $scope.values= values; 
     }) 

回答

3

嘗試ng-options="key as value for (key, value) in values"。我認爲問題在於你試圖同時使用對象的鍵和值,同時試圖引用.Key & .Value,它實際上並不存在。

如果你想要做你的ng-options你原來的方式,你返回的對象應該是這樣的:

var result = [ 
    { Key: 'test1', Value: 'test1Value' }, 
    { Key: 'test2', Value: 'test2Value' } 
] 

要的WebAPI返回對象這樣的方法應該是這樣的:

[HttpGet] 
    public List<KeyValuePair<string, string>> Get() 
    { 
     return new Dictionary<string, string>(){ 
      { "test1", "test 1"}, 
      { "test2", "test 2"} 
     }.ToList<KeyValuePair<string, string>>(); 
    } 
+0

我想要以這種方式返回我的結果。我不知道爲什麼一個字典(這只是一個keyvalue對列表)沒有從WebAPI那樣返回。 –

+0

我會給你答案的答案,並添加我所做的,以獲得WebAPI控制器返回數據作爲鍵值對,將與我的angularjs代碼一起工作。 –