Consuming .NET Types from Javascript

One of the things I’ve found most compelling about mixing up server-side and client-side technologies, is Javascript’s fantastic ability of generating on the fly objects. There are two parts to this awesome little trick, firstly, serialising the object at the server, and reading it at the client.

We’ll imagine, that we have a User list that we want to make available to the client, so let’s design our model.

public class User {

#region Properties public string Username { get; set; } public string Password { get; set; } public string Forename { get; set; } public string Surname { get; set; } #endregion
Code language: PHP (php)

}
There are a number of ways of serialising objects in .NET, but the one we are interested in is JSON (Javascript Object Notation, http://www.json.org). JSON is a lightweight data interchange format that Javascript can evaluate as an object. Now, without Mvc’s goodness, you kinda have to do things yourself, and to do that, you need the DataContractJsonSerializer (which you can find with a reference to System.ServiceModel.Web). Let’s decorate our class and mark the various member’s that we want to serialise.

using System.Runtime.Serialization;

[DataContract]
public class User {

#region Properties [DataMember] public string Username { get; set; } public string Password { get; set; } [DataMember] public string Forename { get; set; } [DataMember] public string Surname { get; set; } #endregion
Code language: PHP (php)

}
By using the DataContract and DataMember attributes, we are marking what members of what types are available to be serialised. This is good because it allows you to customise exactly what members you want, and hide others you don’t. In the above example, we won’t bother making the User.Password property available to the client.

The next step, is to simply call the serialisation, which we’ll dump straight into a HttpResponse output stream.

// Create out sample object instance.
User user = new User() {
Username = “admin”,
Password = “password”,
Forename = “Matthew”,
Surname = “Abbott”
};

// We need to modify the content type so it is interpretted correctly by the browser.
Response.ContentType = “application/javascript”;

// Serialise the object, and write it straight to the output stream.
DataContractJsonSerializer serialiser = new DataContractJsonSerializer(typeof(User));
serialiser.WriteObject(Response.OutputStream, user);

// We can safely close the output stream, nothing more to write.
Response.End();
Thats our server stuff done! Now comes the interesting part!

For the client-side, I always tend to choose JQuery (http://www.jquery.com) over any other Javascript framework, it’s just easy, and what’s even easier is getting our JSON content, as JQuery has nice little support method that automatically evaluates the JSON response for us. getJSON is the key, but of course you can setup your request manually by using $.ajax(…) instead.

var getUser = function(username, callback) {
$.getJSON(“UserEndpoint.aspx”, { “username”: username }, function(result) {
if (callback) {
callback(result);
}
});
};

$(function() {

getUser("admin", function(result) { alert(result.Forename + " " + result.Surname); });
Code language: JavaScript (javascript)

});
And thats it! But wait…what about ASP.NET Mvc I hear you ask? With Mvc, its even easier, as those thoughtful boys over at the ASP.NET Mvc team thought to create the JsonResult, which doesn’t even require you to use the DataContractJsonSerializer! Just chuck a POCO (Plain Old CLR Object) at it, and it should hopefully just go straight ahead and prep some JSON goodness for you.

public ActionResult GetUsername(string username) {
// We won’t both doing some lookup, let’s just create out dummy user.
User user = new User() {
Username = “admin”,
Password = “password”,
Forename = “Matthew”,
Surname = “Abbott”
};

return Json(user);
Code language: JavaScript (javascript)

};
Just update your Ajax calls to suit.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post