AngularJS-通过$http将对象数组传递给MVC控制器
我想了很久,但我找不到解决办法,也许你们中的某个人解决了类似的问题 假设我们希望通过$http服务将对象数组传递给MVC控制器。 这个数组是在angular中创建的,所以我不知道正确的类型(只是var)。 问题是我不知道MVC函数中应该是什么类型的参数 AngularJS控制器AngularJS-通过$http将对象数组传递给MVC控制器,angularjs,asp.net-mvc,service,controller,Angularjs,Asp.net Mvc,Service,Controller,我想了很久,但我找不到解决办法,也许你们中的某个人解决了类似的问题 假设我们希望通过$http服务将对象数组传递给MVC控制器。 这个数组是在angular中创建的,所以我不知道正确的类型(只是var)。 问题是我不知道MVC函数中应该是什么类型的参数 AngularJS控制器 $scope.DoSth = function (){ var data = [{ Id: "1", Value: "apple" }, { Id:
$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
}
有人能帮我吗?如果我没弄错的话,您可以使用stringtype(如果发送了JSON)来实现这一点
You have to put model here.
public string DoSth(FruitModel 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;
};
如果我没弄错的话,您可以使用stringtype(如果发送了JSON)来实现这一点 不要忘记在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;
};
创建一个类
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
}
公共字符串doth(列表数据)
{
//访问您的数据
//数据[0]。Id,数据[0]。值或任何其他方式
}
无需更改任何js代码即可创建类
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
}
公共字符串doth(列表数据)
{
//访问您的数据
//数据[0]。Id,数据[0]。值或任何其他方式
}
无需更改任何js代码您需要类似jackson的东西来将json映射到pojo。您需要类似jackson的东西来将json映射到pojo。感谢回答,我检查了它,但我仍然收到空对象,不知道为什么。感谢回答,我检查了它,但我仍然收到空对象,不知道为什么。感谢回答,Karthik M R的答案更精确感谢答案,Karthik M R的答案更精确无问题。快乐编码!没问题。快乐编码!