0

I have an ASP.NET Web API that accepts a POST with a UserModel in it:

[HttpPost]
public object Post(UserModel userModel)
{
    // some logic here
}

The UserModel is a complex type that looks like this:

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:

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. This is the JSON object I'm sending:

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. The values of the parent object (the UserModel object are ok).

What am I doing wrong here? how can you send a complex object to WebAPI Model?

7
  • It should not be rather [FromBody] UserModel userModel? Commented Apr 23, 2015 at 10:08
  • 1
    I'd definitely double check the JSON being sent up with a tool like Fiddler Commented Apr 23, 2015 at 10:27
  • Perhaps not related but your types don't really match: FirstName and LastName are ints, should be strings Commented Apr 23, 2015 at 11:23
  • Ran your example above, with types corrected for FirstName and LastName and returning void instead of object from the Post method, worked as expected on my machine. Commented Apr 23, 2015 at 11:28
  • @Christian you are right - I've written the code here as an example and copy & pasted without noticing. I will revise the post. thanks. Commented Apr 23, 2015 at 11:49

1 Answer 1

0

to receive complex data objects in MVC web API actions you have to add [FromBody] attribute to your POST arguments.

The [FromBody] tells the Web API to search for the parameter’s value in the body of a POST request.

 [HttpPost]
 public void Post([FromBody] UserModel userModel)
 {

 }

I've made a local test and I obtained the values.

I hope it helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.