martin-brennan

articles / archive / about

.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:

public class ChatMessage
{
    public int ID { get; set; }
    public string Message { get; set; }
    public bool Read { get; set; }
}

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

[HttpPost]
public ActionResult Send( ChatMessage message)
{
    var id = Chat.Send(message);
    return Content(id);
}

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

{
	ID: null,
	Message: "Hey how's it going?",
	Read: false
}

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.

  • 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