Backbone and ASP.NET MVC: Use Nullable types as Id

As a side note to my blog post about renaming the idAttribute in Backbone when using it with ASP.NET (MVC), this post continues with the Id attribute.

The Id attribute in Backbone is very important. Backbone uses it to determine if an object is new, or already existed. Collections use it to determine if it already contains any given object.

So I ran into a problem in a situation where my model required a lot of “supporting data” before it was saved. To add this data, I decided to create the models on the server and add it to a collection (since there were a whole list of them).

No matter how many models I added to the list, only the first one was rendered. Why? Because my model on the server was using a non-nullable Integer as its Id property like this:

public class Account { public int Id { get; set; } }

So of course, all the models returned from the server had an Id of zero! And of course, Backbone thought that they were all the same instance since they shared the same Id.

Small change, huge impact

Talk about a single character making a huge impact!

By adding the silly question mark to the Id property, everything was working. That’s because a Nullable integer is not added to the JSON returned by the server, and Backbone then knows that this model does not exist!