Send Date Time Objects with JQuery to Asp.Net MVC

I was looking for a way to create objects on the client side with JQuery and send them by ajax to a MVC controller, I want to be able to fill my objects with DateTime instances and then serialize them in such a way that they will be auto mapped to the corresponding C# object. In order to accomplish this I had to format the date with JavaScript in some way that whatever the time zone is on the client side, I will get on the controller the local time of the host IIS server.


Sending simple date object

On the controller side I’ve created a method that accepts a DateTime parameter:

HomeController.cs
        [HttpPost]
        public JsonResult ValbyPost(DateTime inputDate)
        {
            return Json(new
            {
                Data = inputDate.ToString()
            });
        }

On the client side I’ve created a new Date object with JQuery, then the date is formatted to ISO UTC format and sent over ajax:

Index.cshtml
<script src="@Url.Content("~/Scripts/date.format.js")" type="text/javascript"></script>
<script type="text/javascript">

    $('#btn1').click(function () {
        var myVal = new Date();
        //format the date for the controller – c#
        myVal = dateFormat(myVal, 'isoUtcDateTime');
        //send to server
        $.ajax({
            type: "POST",
            url: "Home/ValbyPost",
            dataType: "JSON",
            data: { inputDate: myVal },
            success: function (data) {
                alert('Http POST – ' + data.Data);
            }
        });
    });

</script>

Since my time zone +2GMT I expect to get the right result in C#, when inspecting the http POST with Firebug this is the outcome:

Sent data:  2011-05-17T22:43:53Z (client side UTC)

Received data: 5/18/2011 1:43:53 AM (server side +2GMT)

Notice that I am using the dateFormat method from the date.format.js, this helper is created by Steven Levithan back in 2007 and is a ColdFusion-inspired script, you can read more about it on this post.

Sending complex date object

Another frequent case is when you have a class defined in C# that contains DateTime members and you want to create and send with JQuery this object to the server. I’ve created a demo class named History that has several properties like this:

DateTimeMvc.Models.History.cs
    public class History
    {
        public DateTime LastModified { get; set; }
        public List<DateTime> Versions { get; set; }
    }

And on the in the Home controller there is a C# method that has a parameter of type History:

HomeController.cs
        [HttpPost]
        public JsonResult ObjbyPost(History history)
        {
            string msg = string.Empty;
            if (history.Versions != null && history.Versions.Count > 0)
            {
                foreach (var item in history.Versions)
                {
                    msg += " " + item.ToShortDateString() + " ";
                }
            }

            return Json(new
            {
                Data = msg.Length > 0 ? msg : " NO data"
            });
        }

And this is how you can create and format the History object in JQuery in order to send the object by ajax to the server:

Index.cshtml
    $('#btn2').click(function () {
        //make some data
        var myVal = new Date();
        myVal = dateFormat(myVal, 'isoUtcDateTime');

        var dt1 = new Date().setYear(2010);
        var dt2 = new Date().setYear(2009);
        dt1 = dateFormat(dt1, 'isoUtcDateTime');
        dt2 = dateFormat(dt2, 'isoUtcDateTime');

        //create a new history object in js same as in c#
        var history = {
            LastModified: myVal,
            Versions: new Array()
        }

        //create history entries
        history.Versions.push(dt1);
        history.Versions.push(dt2);

        //send to server using http post
        $.ajax({
            type: "POST",
            url: "Home/ObjbyPost",
            contentType: "application/json; charset=utf-8",
            dataType: "JSON",
            data: JSON.stringify(history),
            success: function (data) {
                alert('Http POST – ' + data.Data);
            }
        });
    });

After creating the date object with JQuery the iso format is applied, then the History object is stringify with JSON and sent to the controller, as in the first example the History class instance is received in C# with the right time zone. But if you’ll change from POST to GET this method will fail and the controller will receive null instead of dates. After debugging with Firebug I’ve come to the conclusion that the MVC will not auto deserialize the json object so I’ve changed the method to receive a string and did a manual deserialization with JavaScriptSerializer. 

HomeController.cs
        [HttpGet]
        public JsonResult ObjbyGet(string history)
        {
            var serializer = new JavaScriptSerializer();
            var obj = serializer.Deserialize<History>(history);

            string msg = string.Empty;
            if (obj.Versions != null && obj.Versions.Count > 0)
            {
                foreach (var item in obj.Versions)
                {
                    msg += " " + item.ToShortDateString() + " ";
                }
            }

            return Json(new
            {
                Data = msg.Length > 0 ? msg : " NO data"
            }, JsonRequestBehavior.AllowGet);
        }

Changes on the client side code:

Index.cshtml
        //send to server using http get
        $.ajax({
            type: "GET",
            url: "Home/ObjbyGet",
            dataType: "JSON",
            data: { history: JSON.stringify(history) },
            success: function (data) {
                alert('Http GET – ' + data.Data);
            }
        });

Be careful when using Http GET, it’s not suitable for large objects because the size is limited and by default is ASCI encoded, the Http POST is slower but as you see in the above code you can send object directly without needing the JavaScriptSerializer.

download source code files

Beside this code, the demo project contains a search form with a start date and a end date that are serialized with JQuery, check it out. The project is made with Asp.Net MVC 3 and JQuery 1.6.1, in order to run it you’ll need VS.NET 2010 and the MVC Tools Update installed.

One Response to Send Date Time Objects with JQuery to Asp.Net MVC
  1. Pavel Reply

    If you use date with timezone and timezone is important part for your busines-logic’s, the best way is on server-side use DateTimeOffset instead DateTime, which supports timezone as part of date (also we can get DateTime part using property DateTime).

Leave a Reply

Your email address will not be published. Please enter your name, email and a comment.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>