Monday, June 17, 2013

Posting multiple parameters to a Web API project using jQuery

Ok this one had me stumped.  I was trying to pass multiple parameters to a Web API method using jQuery but no data would bind to my data transfer object when the method executed.

*Note that this is a good example of how to pass multiple parameters to a Web API method when you take the issue discussed into consideration

The Controller

public class UserDTO
{
   public int userID;
   public string username;
}

[HttpPost]
public string Post([FromBody]UserDTO userDTO)
{
   return userDTO.userID.ToString() + " " + userDTO.username;
}

The Web API route config

config.Routes.MapHttpRoute(
   name: "DefaultApi",
   routeTemplate: "api/{controller}/{id}",
   defaults: new { id = RouteParameter.Optional }
);

The jQuery

var apiUrl = "http://localhost:55051/api/User";
var userDTO = {
   userID: 5,
   username: "testuser"
};

$.ajax({
   type: "POST",
   url: apiUrl,
   data: JSON.stringify(userDTO),
   datatype: "json",
   contenttype: "application/json; charset=utf-8"
)};

Fiddler Output

Fiddler shows correctly passed JSON variables and in the Raw view I can see:
{"userID":5,"username":"testuser"}

On Execution

userID = 0
username = null

The Issue?

Case sensitivity on the .ajax jQuery call:
  • datatype should be dataType
  • contenttype should be contentType
Thanks to those at StackOverflow for assistance with this one!