Serialization In ASP.NET MVC

I’ve been doing a lot more with jQuery in ASP.NET MVC than I ever have before. One of the biggest problems I’ve had is in the sending back of JSON to jQuery ajax calls, it seems that the built in MVC action result is not to friendly with dates and/or forms submitted with uploaded files, so with some help of an article @ http://msmvps.com/blogs/omar/archive/2008/10/03/create-rest-api-using-asp-net-mvc-that-speaks-both-json-and-plain-xml.aspx I’ve come up with my own SerializeResult<T>

 

Usage:

To send back JSON for a ajax submit without a file upload:

result = new SerializeResult<Models.CheckPassword.Response>(model.Result, enSerializeResultFormat.Json);
 

To Send back JSON for an ajax submit with a file upload:

result = new SerializeResult<Models.UploadFile.ReceiveFile.Response>(model.Result, enSerializeResultFormat.JsonTextArea);

 

All you have to do is decorate your classes with “[DataContract]” and “[DataMember]” attributes

 

ex:

    [DataContract]
    public class Client
    {
      [DataMember] public int? ClientID;
      [DataMember] public string CompanyName;

      [DataMember] public decimal PriorPriorYearSalesTotal;
      [DataMember] public decimal PriorYearSalesTotal;
      [DataMember] public decimal CurrentYearSalesTotal;
      [DataMember] public decimal SalesTotal;

      public Client()
      {
        ClientID = null;
        CompanyName = string.Empty;

        PriorPriorYearSalesTotal = 0;
        PriorYearSalesTotal = 0;
        CurrentYearSalesTotal = 0;
        SalesTotal = 0;
      }
    }

Here is the

Code:

 

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Runtime.Serialization.Json;

//http://msmvps.com/blogs/omar/archive/2008/10/03/create-rest-api-using-asp-net-mvc-that-speaks-both-json-and-plain-xml.aspx

namespace ISI.Libraries.MVC
{
  public enum enSerializeResultFormat
  {
    Auto,
    Xml,
    JavaScript,
    Json,
    JsonTextArea
  }

  [AspNetHostingPermission(System.Security.Permissions.SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(System.Security.Permissions.SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  public class SerializeResult<T> : ActionResult
  {
    private static UTF8Encoding UTF8 = new UTF8Encoding(false);

    public T Data { get; set; }
    public Type[] IncludedTypes = new Type[] { typeof(object) };
    public enSerializeResultFormat SerializeFormat = enSerializeResultFormat.Auto;


    public SerializeResult(T data, Type[] extraTypes, enSerializeResultFormat serializeFormat)
    {
      this.Data = data;
      this.IncludedTypes = extraTypes;
      this.SerializeFormat = serializeFormat;
    }
    public SerializeResult(T data, enSerializeResultFormat serializeFormat) : this(data, new Type[] { typeof(object) }, serializeFormat) { }
    public SerializeResult(T data, Type[] extraTypes) : this(data, extraTypes, enSerializeResultFormat.Auto) { }
    public SerializeResult(T data) : this(data, new Type[] { typeof(object) }) { }


    public override void ExecuteResult(ControllerContext filterContext)
    {
      if(SerializeFormat == enSerializeResultFormat.Auto)
      {
        SerializeFormat = ((filterContext.HttpContext.Request.Headers["Content-Type"] ?? string.Empty).ToLower().Contains("application/json") ? enSerializeResultFormat.Json : enSerializeResultFormat.Xml);
      }

      switch (SerializeFormat)
      {
        case enSerializeResultFormat.Xml:
          using (System.IO.MemoryStream oStream = new System.IO.MemoryStream())
          {
            ISI.Libraries.XML.Serialize<T>(this.Data, oStream);

            new ContentResult { ContentType = "text/xml", Content = UTF8.GetString(oStream.ToArray()), ContentEncoding = UTF8 }.ExecuteResult(filterContext);
          }
          break;

        case enSerializeResultFormat.Json:
          using (System.IO.MemoryStream oStream = new System.IO.MemoryStream())
          {
            new DataContractJsonSerializer(typeof(T)).WriteObject(oStream, this.Data);

            new ContentResult { ContentType = "application/json", Content = UTF8.GetString(oStream.ToArray()), ContentEncoding = UTF8 }.ExecuteResult(filterContext);
          }
          break;

        case enSerializeResultFormat.JsonTextArea:
          using (System.IO.MemoryStream oStream = new System.IO.MemoryStream())
          {
            new DataContractJsonSerializer(typeof(T)).WriteObject(oStream, this.Data);

            new ContentResult { ContentType = "text/html", Content = string.Format("<textarea>{0}</textarea>", UTF8.GetString(oStream.ToArray())), ContentEncoding = UTF8 }.ExecuteResult(filterContext);
          }
          break;

        case enSerializeResultFormat.JavaScript:
          new JsonResult { Data = this.Data }.ExecuteResult(filterContext);
          break;
      }
    }
   
  }
}
Published 06/01/2009 15:12:09 (UTC) by Ron Muth

kick it on DotNetKicks.com  Shout it  vote it on WebDevVote.com

Comments

DotNetShoutout Serialization In ASP.NET MVC

10/02/2009 10:40:25 by DotNetShoutout
Thank you for submitting this cool story - Trackback from DotNetShoutout

Servefault.com Serialization In ASP.NET MVC

10/03/2009 09:39:38 by Servefault.com
Thank you for submitting this cool story - Trackback from Servefault.com

DotNetKicks.com Serialization In ASP.NET MVC

10/23/2009 19:43:41 by DotNetKicks.com
You've been kicked (a good thing) - Trackback from DotNetKicks.com

DotNetBurner - ASP.net MVC Serialization In ASP.NET MVC

10/23/2009 19:49:14 by DotNetBurner - ASP.net MVC
DotNetBurner - burning hot .NET content

WebDevVote.com Serialization In ASP.NET MVC

10/28/2009 03:13:32 by WebDevVote.com
You are voted (great) - Trackback from WebDevVote.com

Leave a Comment

(required)
(required)
(optional, never published)
(optional)
(required)