2016-04-21 131 views
0

我想知道很長一段時間,我找不到解決方案,也許有人解決了類似的問題。

比方說,我們想通過和對象數組通過$ http服務到MVC控制器。 這個數組是創建在角度,所以我不知道正確的類型(只是VAR)。 問題是我不知道應該是什麼類型參數的MVC功能

AngularJS控制器

$scope.DoSth = function(){ 
    var data = [{ 
     Id: "1", 
     Value: "apple" 
    }, 
    { 
     Id: "2", 
     Value: "banana" 
    }]; 
}; 

//DoSthService injected into angular controller 

DoSthService.doSth(data) 
    .success(function(result){ 
     //sth with success result 
    }) 
    .error(function(result){ 
     //sth with error result 
    }); 

AngularJS服務:

this.doSth = function(data){ 
    var response = $http({ 
     method: "post", 
     url: "Home/DoSth", 
     data: data 
     //or data: JSON.stringify(data) ?? 
     }); 
    return response; 
}; 

MVC控制器:

public string DoSth(**what type here?** data) 
{ 
    //do sth and return string 
} 

可能a nyone幫助我嗎?

+0

您需要像傑克遜那樣將json映射到pojo。 – skubski

回答

1

創建一個類

public class MyClass 
{ 
    public int Id { get; set;} 
    public string Value { get; set;} 
} 

使用你的方法

public string DoSth(List<MyClass> data) 
{ 
    //access your data 
    //data[0].Id,data[0].Value or by any other way 
} 

無需更改任何列表中選擇您js代碼

+0

Yeee!它正在工作!謝謝! –

+0

沒問題。快樂的編碼! –

0
You have to put model here. 

public string DoSth(FruitModel data) 
{ 
    //do sth and return string 
} 
+0

感謝您的回答,Karthik男R的答案更精確 –

0

如果我沒有記錯,你可以做到這一點與stringtype(如果JSON發送)

public string DoSth(string data) 
{ 
    //do sth and return string 
} 

不要忘了在你的AJAX請求添加此頭:

headers: { 
    'Content-Type': 'application/json' 
} 

而且它字符串化,如:

data: JSON.stringify(data) 

如果你這樣做是正確的AJAX請求應該是這樣的:

this.doSth = function(data){ 
    var response = $http({ 
      method: 'post', 
      url: 'Home/DoSth', 
      headers: { 
       'Content-Type': 'application/json' 
      }, 
      data: JSON.stringify(data) 
     }); 
    return response; 
}; 
+0

感謝您的答案,我檢查了它,但我仍然收到零對象,不知道爲什麼。 –

相關問題