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

burtono  adult previews
11/12/2011 00:05:20 by burtono
hello everyone! where can I find top adult previews? This only have I found [url=http://www.hqpornspots.com/manojob/]Mano Job[/url] thanks

breckenridged  adult video preview
11/12/2011 00:05:22 by breckenridged
hello everyone! where can I find top adult video preview? This only have I found [url=http://www.hqpornspots.com/perfectflex/]Perfect Flex[/url] thanks

Berochorn  ????? ??????? ???????????
11/29/2011 08:40:59 by Berochorn
[url=http://porn-bolt.ru/][img]http://porn-bolt.ru/scj/thumbs/31/361.jpg [/img][/url] [url=http://porn-bolt.ru/][img]http://porn-bolt.ru/scj/thumbs/4/382.jpg [/img][/url] [url=http://porn-bolt.ru/]??????? ? ?????? ????? ????? [/url] ????? ?????????, ??? ????? ???? ?????????, ? ? - ???????? ? ???????. [b]???????? ????? ??????? [/b] - [url=http://porn-bolt.ru/]???????? ??????? ????? [/url] ?????? ??????????: ??? ???????? ??????. ???????? ??? ???? ?????? ??????? ??? ???????.

frenakedpicsr  investicijsko svetovanje
01/14/2012 02:32:00 by frenakedpicsr
podjetniško svetovanje [url=http://www.varcevanje.info]varcevanje[/url]

frenakedpicst  auto net
01/28/2012 11:32:51 by frenakedpicst
naložba v zlato [url=http://www.ilirikadzu.info]ilirika dzu[/url]

nudecelebsk  naložba v delnice
01/28/2012 11:32:51 by nudecelebsk
naložba v delnice [url=http://www.nepremicninenet.info]nepremicnine.net[/url]

nonnudesp  racunovodsko svetovanje
02/03/2012 04:00:53 by nonnudesp
pravno svetovanje [url=http://www.kamvlozitidenar.info]kam vloziti denar[/url]

Leave a Comment

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