[英]ASP.NET Web API - pass a complex type from javascript json
I have an ASP.NET Web API that accepts a POST with a UserModel in it: 我有一个ASP.NET Web API,它接受其中带有UserModel的POST:
[HttpPost]
public object Post(UserModel userModel)
{
// some logic here
}
The UserModel is a complex type that looks like this: UserModel是一个复杂的类型,如下所示:
public class UserModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public AddressModel CurrentAddress { get; set; }
}
The AddressModel
Model looks like this: AddressModel
模型如下所示:
public class AddressModel
{
public string Country { get; set; }
public string City { get; set; }
public string Street { get; set; }
public string Number { get; set; }
}
I'm trying to call this API from javascript and send a JSON object. 我正在尝试从JavaScript调用此API并发送JSON对象。 This is the JSON object I'm sending:
这是我要发送的JSON对象:
var user = {
Id: 1,
FirstName: 'Hello',
LastName: 'World',
CurrentAddress: {
Country: 'Israel',
City: 'Tel Aviv',
Street: 'Shalom',
Number: '5'
}
};
What I get in my Post method is a UserModel
with the UserModel fields filled with the correct information, the CurrentAddrent address is initialized, but the values sent are not there. 我在Post方法中得到的是一个
UserModel
其中的UserModel字段填充了正确的信息,CurrentAddrent地址已初始化,但发送的值不存在。 The values of the parent object (the UserModel
object are ok). 父对象的值(
UserModel
对象可以)。
What am I doing wrong here? 我在这里做错了什么? how can you send a complex object to WebAPI Model?
如何将复杂对象发送到WebAPI模型?
to receive complex data objects in MVC web API actions you have to add [FromBody] attribute to your POST arguments. 要在MVC Web API操作中接收复杂的数据对象,必须将[FromBody]属性添加到POST参数中。
The [FromBody] tells the Web API to search for the parameter's value in the body of a POST request. [FromBody]通知Web API在POST请求的正文中搜索参数的值。
[HttpPost]
public void Post([FromBody] UserModel userModel)
{
}
I've made a local test and I obtained the values. 我进行了本地测试,并获得了值。
I hope it helps! 希望对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.