.NET MVC 4 Model Binding Null on Post

This was an extremely frustrating problem I came across when building an API using .NET MVC 4. I was using HTTP POST to send a model to the API using JSON, and relying on the built in Model-binding to correctly interpret the JSON and convert it to a model. However, for one particular model none of the properties were binding correctly. After a lot of head scratching and threatening my computer screen, I found this post by Anders Åberg:

.NET MVC 4 Model Binding null on POST

Basically, take this model for an example of how the problem occurs. This represents a message in some sort of chat system:

And your API for example has a Controller method that accepts a HTTP POST request to add a new message:

And then the JSON POST body would look something like this:

You would expect that the model would be bound correctly and that all the properties would be filled in correctly right? Right?! WRONG! Because I’ve named the parameter for the Send method the same thing as one of the model’s properties, Message. This really confuses the model binder because it’s trying to just use the message property and binding it to the model, instead of just counting as a property of the model.

There are two things you can do to get around this:

  1. 1. Don’t name any of your method parameters the same thing as any of your model’s properties! E.g. newMessage instead of message.
  2. 2. Don’t name your model properties anything similar to the name of the model class, as you may want to use it as a variable name. E.g. MessageText instead of Message.

Last modified on Monday December 30 2013 @ 05:26pm.

  • Brett Andrews

    Very interesting. I’ll tuck that piece of info away in case I come across it later (I’m assuming web API will have the same problem). I believe a 3rd option would be:
    {message: chatMessage} //where chatMessage is your ChatMessage (sorry for poor formatting; I’m on my phone )

  • Anders

    fuck me, this post helped me, how can I +1/upvote this blog?

    • http://www.martin-brennan.com/ Martin Brennan

      Thanks Anders glad I could help haha! Just share it wherever you want to (facebook, google+, twitter, redit etc.) Go wild!

  • الر عد

    you saved my life, thanks

  • Timmi

    THANK YOUUU! You are my new Insperation!!!! Had the same problem, and took me hours! But now it WORKS <3

    • http://www.martin-brennan.com/ Martin Brennan

      Hahaha glad I could help!

  • Ric

    this is crazy. I’ve been doing MVC for quite some time now and I’ve never seen this before. Renaming the param worked for me too. Thanks for the tip!

  • tic

    Really appreciated. This was driving me insane

  • Pingback: Martin Brennan | Sensible .NET REST APIs()