Sometimes when performing ajax databinding with the MVC grid you may end up with unexpected result: server error 500.
What is even stranger is that server-side binding works as expected with the same data binding code. Let’s demystify this problem:
You will see the following if you use FireBug or Fiddler to inspect the response:
The error message is “A circular reference was detected while serializing an object of type” followed by some type. If you google this up you will find out that this exception is thrown by the JavaScriptSerializer class because of circular references detected. “What the heck is a circular reference anyway?” you may ask. In my example it is the well known Orders-Customers relationship:
Most O/R mapping tools (it is Entity Framework in my case) would create reference properties. In this case the Orders object will have a Categories property and the Categories object will have an Orders prooperty:
Since the MVC grid is ajax-bound to Orders the JavaScriptSerializer will try to serialize the data. During that process it tries to serialize all properties of the Orders type which includes “Categories” as well. However when traversing the Categories object the JavaScriptSerializer discovers the circular reference (the Orders property) and gives up by throwing the aforementioned exception.
There are three possible solutions of this problem:
public class OrderViewModel
{
public int OrderID
{
get;
set;
}
public DateTime? OrderDate
{
get;
set;
}
}
public ActionResult Index()
{
var model = from o in new NorthwindEntities().Orders
select new OrderViewModel
{
OrderID = o.OrderID,
OrderDate = o.OrderDate
};
return View(model);
}
[GridAction]
public ActionResult AjaxIndex()
{
var model = from o in new NorthwindEntities().Orders
select new OrderViewModel
{
OrderID = o.OrderID,
OrderDate = o.OrderDate
};
return View(new GridModel
{
Data = model
});
}
I hope this helps!