Excluding properties from being serialized in ASP.NET MVC JsonResult

7. October 2009 18:19

Lately I have been working a lot on a large AJAX-application based on ASP.NET MVC. Every AJAX request goes to a controller action that returns a model class serialized to JSON.

A typical controller action like that could be:

public JsonResult ShowUser(int id)
{
User user = dataLayer.GetUserByID(id);
return Json(user);
}

In the example above, all the public properties of the User class will be serialized into the JSON object. When working with large model classes (in this case the User class), you often want to have some special properties you can use for keeping track the object state, for example IsEmpty or IsValid. These are not strictly part of the model data but are useful when manipulating the objects in the C# code. They are often not necessary in the Javascript that will render the objects.

I just found out that it is possible to exclude such properties from being serialized by ASP.NET MVC - you just have to add a [ScriptIgnore] attribute on them.

Consider the following (simplified) case:

public class User
{
public int Id { get; set; }
public string Name { get; set; }
[ScriptIgnore]
public bool IsComplete
{
get { return Id > 0 && !string.IsNullOrEmpty(Name); }
}
}

In this case, only the Id and the Name properties will be serialized, thus the resulting JSON object would look like this:

{ Id: 3, Name: 'Test User' }

Without the [ScriptIgnore] attribute, the serialization process would include both the computation and transport overhead of having to deal with the IsComplete field, which in many cases is just an unnecessary performance hit. When dealing with large websites, every CPU cycle and every byte counts.

location.hash javascript bug in Firefox 3.0

2. October 2009 13:02

After struggling for awhile trying to figure out a problem with resetting the URL hash (also called the URL fragment) in Javascript, I discovered a bug in Firefox 3.0.

When setting location.hash to en empty string in Firefox 3.0, it will cause a page reload. To solve, use location.hash = '#' instead. This will also work in all other major browsers. The issue appears only in Firefox version 3.0.* - it seems to have been fixed in 3.5.

This might be a useful point to remember if you are writing a lot of cross-browser Javascript.

Archive