ASP.NET MVC Web API and primitive types

An explanation of how Web API binds primitive types from the HTTP body

Back to blog

In standard ASP.NET MVC, the in-built model binder translates URL encoded form data from a POST request into primitive typed parameters on controller action methods.  For example, if you have an action method,

and submit a HTTP request with form data,

MVC will bind the comment parameter to the value ‘a user entered comment’.

This doesnt work in web api. If you have a similar action method in a  HttpController and submit a HTTP POST with the same form data, the comment parameter is always null. This is because Web API can only bind a single primitive type from the HTTP body and the form data has to be in the format,

which you post in jquery by specifying an empty parameter name for your post data,

Also, you have to tag the action method parameter in mvc with the FormBody attribute,

There are good reasons for this as explained here but it breaks the principal of least surprise and is confusing if you are familiar with MVC.

Edit – if you reallllyyyyyly want to bind multiple POST parameters, Rich Strahl wrote a custom Value Provider – see http://www.west-wind.com/weblog/posts/2012/Sep/11/Passing-multiple-simple-POST-Values-to-ASPNET-Web-API

As you read this far, you should follow me on twitter here.