Monday, October 29, 2012

Using F# Records with ASP.NET Web API

In the Knockout.js and Backbone.js examples that I provided over the last few weeks, the model was written as a class using the traditional syntax. Here's an example:

type Contact() =
let mutable firstName = ""
let mutable lastName = ""
let mutable phone = ""
member x.FirstName with get() = firstName and set v = firstName <- v
member x.LastName with get() = lastName and set v = lastName <- v
member x.Phone with get() = phone and set v = phone <- v
view raw gistfile1.fs hosted with ❤ by GitHub
While this approach works well, it would be great if we could use F# records instead. It turns out that with a few tweaks, this is easy to accomplish. Let's see how to do this in the Knockout.js example.  

First, we'll change the model to be an F# record. The new model looks like this:

type Contact = { FirstName : string; LastName : string; Phone : string }
view raw gistfile1.fs hosted with ❤ by GitHub
We'll also need to change how the example data is initialized. This code now looks like this:

let contacts = seq { yield { FirstName = "John"; LastName = "Doe"; Phone = "123-123-1233" }
yield { FirstName = "Jane"; LastName = "Doe"; Phone = "123-111-9876" } }
view raw gistfile1.fs hosted with ❤ by GitHub
Lastly, a small change is needed in the ContactsViewModel. This now looks like the following:

No comments:

Post a Comment