我正在尝试使用 AngularJS 将 JavaScript 项目发布到 C# WebAPI 调用。以下是我正在尝试做的事情。
对象
class Address
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
}
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address address { get; set; }
}
我的 C# Controller 函数
[Route("Update/")]
public void Update(Person person)
{
_service.Update(person);
}
AngularJS 调用
this.update = function (person) {
$http.post("api/Person/Update/", person);
}
当我在 WebAPI Controller 中收到对象时,地址为空。为什么没有收到此数据?
编辑 我原来的问题错了,Person 对象看起来像这样
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public IAddress address { get; set; }
}
当我将地址从 IAddress 更改为 Address 时,一切都按预期工作。
最佳答案
您的帖子将采用 json 格式,它将 person 对象分配给 person
,Address
对象必须是格式正确的对象,因为它包含子属性。
代码
$scope.person = {
'Street': '',
'LastName': '',
'Address': {
'Street': '',
'City': '',
'State': '',
},
}
this.update = function (person) {
$http.post("api/Person/Update/", { person : $scope.person});
}
关于javascript - 从 AngularJS 将复杂对象传递给 WebAPI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31014111/