tisdag 30 december 2008

Making the JsonResult in MVC ignore a property

In MVC each controller action returns an "ActionResult". This can be a View, Content (plain text) or JsonResult for example. With JsonResult the output will (obviously) be serialized to JSON.

However - when using any serializeri on classes with bi-directional fields/properties you will run into problems as the serialization will lead to a endless loop trying to follow the bi-directional fields back and forth.

Using other serializer such as an XML serializer for example you just tag the bi-directional property with an "XMLIgnore" attribute and the serializer will basically ignore the field during serialization.

But trying to find a way for the JsonResult was not very easy as there is basically no subjects on this to be found using Google (at this time). However, using Reflector I found that the JsonResult is using the serializer "JavaScriptSerializer" found in "System.Web.Scrtipt.Serializer" (System.Web.Extensions.dll version 3.5). Following the code I found that the attribute to use to ignore a field is "ScriptIgnore" also found in "System.Web.Script.Serialization".

So, problem solved: Use the "ScriptIgnore" attribute to make the Json serializer in MVC ignore your bi-directional fields!

Inga kommentarer: