AngularJS - 通过$ http将对象数组传递给MVC控制器
我想知道很长一段时间,我找不到解决方案,也许有人解决了类似的问题。
比方说,我们想通过和对象数组通过$ 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帮助我吗?
创建一个类
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代码
Yeee!它正在工作!谢谢! –
没问题。快乐的编码! –
You have to put model here.
public string DoSth(FruitModel data)
{
//do sth and return string
}
感谢您的回答,Karthik男R的答案更精确 –
如果我没有记错,你可以做到这一点与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;
};
感谢您的答案,我检查了它,但我仍然收到零对象,不知道为什么。 –
您需要像杰克逊那样将json映射到pojo。 – skubski