Backbone and ASP.NET MVC: Rename the ID attribute

In Backbone, a model’s ID attribute is vital in the way Backbone handles models and collections. In a collection, you can call get with an ID and you’ll get back the model.

The thing is, naming conventions across languages does not always agree. In .Net properties are named in PascalCase. In JavaScript camelCase is the standard, so naturally this leads to a conflict when your model in Backbone names the ID attribute id, and the corresponding domain model on the server side is named Id.

I was using an ASP.NET MVC controller to return a collection of Accounts, but when it hit the client, got changed and later saved, the ID was lost and the model was created as a new instance in the database.

The problem was that when Backbone fetched the collection, and automatically turned the objects in the array into instances of Account — Backbone was expecting to find every model’s ID in the id property, which did not exist. And on the server, it uses Id to know if this model is new or already exists.

Change the idAttribute

It turns out that Backbone is designed for this.

Whenever you define your models, you need to set the value of the idAttribute property like this:

var Account = Backbone.Model.extend({
	idAttribute: "Id"
});

But that’s a bit annoying since you’ll have to remember this on each and every model. And you need to define your own model every time, you can’t just create a new instance of the stock Backbone.Model class.

But with JavaScript being the awesome language that it is, you can change the prototype like this:

Backbone.Model.prototype.idAttribute = "Id";

And now you can totally forget about this, and let Backbone handle IDs properly!