2

I am trying to call a POST API controller. The controller gets called but the complex object comes in empty. I have ran Fiddler and the object is even coming through populated there. What am I doing wrong?

My C# object

public class RegisterUser
{
    public Guid PersonId { get; set; }
    public string Email { get; set; }
    public string Business { get; set; }
    public string EmployeeNumber { get; set; }
    public string UserName { get; set; }
}

API Post Controller

public HttpResponseMessage Post(RegisterUser user)
{
   //This is where the problem is. Everything in user is null 
   //even though I can see it coming through on Fiddler.
}

Javascript code

function User(personId, userName, email, business, employeeNumber) {
   this.PersonId = personId;
   this.Email = email;
   this.Business = business;
   this.EmployeeNumber = employeeNumber;
   this.UserName = userName;
}

function RegisterUser(url) {
   var createdUser = new User("b3fd25ba-49e8-4247-9f23-a6bb90a62691", "username", "email", "business", "56465");
   $.ajax(url, {
       data: JSON.stringify({ user: createdUser }),
       type: "post",
       contentType: "application/json"
  });
}

Web API Route Config

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "RegisterApi",
            routeTemplate: "api/{controller}/{user}"
        );
    }
}
4
  • The AJAX call is asynchronous and it looks like you're executing the resulting code before any data is returned. Commented Jan 24, 2013 at 17:26
  • 1
    The problem is the API controller RegisterUser object is not being populated...The js ajax doesn't even have a return yet. Commented Jan 24, 2013 at 17:30
  • Do you have the HttpPost attribute on the action? Commented Jan 24, 2013 at 17:55
  • It is a mvc web api controller. You don't have to specify anymore. Commented Jan 24, 2013 at 17:59

1 Answer 1

3

createdUser already contains the data needed by Web.Api in the correct format there is no need to wrap it inside an user property which confuses the model binder.

Just write data: JSON.stringify(createdUser) and it should work fine:

function RegisterUser(url) {
   var createdUser = new User("b3fd25ba-49e8-4247-9f23-a6bb90a62691", "username", "email", "business", "56465");
   $.ajax(url, {
       data: JSON.stringify(createdUser),
       type: "post",
       contentType: "application/json"
  });
}

The principles of the model binding are simple until you have matching property names and object structure in your JS and C# objects and it should work fine.

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.