Lately I’ve been playing around with Asp.Net Mvc. I’m trying to adapt the NerdDinner sample for a project I’m working on. The sample includes a class called PaginatedList<T>.  PaginatedList<T> looks something like this:

   public class PaginatedList<T> : List<T>
   {
        public int PageIndex  { get; private set; }
        public int PageSize   { get; private set; }
        public int TotalCount { get; private set; }
        public int TotalPages { get; private set; }
   }

My controller method looks something like this:

   public ActionResult FindBusinessesByName(string businessName, int limit, int page)
   {
      BusinessRepository repository = new BusinessRepository();
      PaginatedList<Business> paginatedBusinesses = new PaginatedList<Business>(repository.FindBusinessesByName(businessName), page, limit);
      return Json(paginatedBusinesses);
   }

I’m using jQuery to get a PaginatedList of businesses from my controller. I use the list of businesses to create an unordered list to display the business information. I haven’t played with jQuery or json serialization much so I was surprised to see that only the business data was returned. The extra properties on the PaginatedList were not. I dug around a bit and downloaded the newly released source for Mvc (woot!). I found the two lines in JsonResult.cs that do the serialization:

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                response.Write(serializer.Serialize(Data));

A quick search for JavaScriptSerializer shows that List<T> becomes an “Array that uses JSON array syntax”. So it appears that since PaginatedList<T> derives from List<T> the serializer ignores the properties on the PaginatedList.

I was able to work around this by changing my controller method to this:

        public ActionResult FindBusinessesByName(string businessName, int limit, int page)
        {
            BusinessRepository repository = new BusinessRepository();
            PaginatedList<Business> paginatedBusinesses = new PaginatedList<Business>(repository.FindBusinessesByName(businessName), page, limit);
            var paginationContainer = new
            {
                PageIndex = paginatedBusinesses.PageIndex,
                PageSize = paginatedBusinesses.PageSize,
                TotalCount = paginatedBusinesses.TotalCount,
                TotalPages = paginatedBusinesses.TotalPages,
                Businesses = paginatedBusinesses
            };
            return Json(paginationContainer);
        }



Reader's Comments

  1. James Stevenson | October 8th, 2009 at 10:48 am

    You rock I just ran into this same issue. Thanks for saving me a ton of time.

Leave a Comment