Steven
Steven

Reputation: 18859

Passing a date with JSON to .NET

Here is my jQuery code:

function onSaveClicked()
{
    var message = 
    {
        MessageID: $("#MessageID").val() || 0,
        MessageDate: "\/Date(<%= DateTime.Now.Ticks %>)\/",
    };


    $.ajax({
       url: "<%= Url.Action("SaveMessage") %>",
       type: "POST",
       dataType: "json",
       data: $.toJSON(message),
       contentType: "application/json; charset=utf-8",
       success: function(result) {
            if (result && result.success)
            {
                //
            }
       }
   }); 
}

At first, I was just setting MessageDate to a string that was in a date format, but after some errors there, I did some research and it looks like I need to pass in the Ticks. But I get the following error:

There was an error deserializing the object of type Models.MessageModel. The value '634185025866884281' cannot be parsed as the type 'DateTime'

I've also tried:

MessageDate: "\\/Date(<%= DateTime.Now.Ticks %>)\\/",

but I get this error message:

There was an error deserializing the object of type Models.MessageModel. DateTime content '/Date(634185027273624742)/' does not start with '/Date(' and end with ')/' as required for JSON.

What do I need to do to get this working?

EDIT: I'm using this to deserialize the JSON request:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
    {
        var serializer = new DataContractJsonSerializer(RootType);
        //RootType here is (Name = "MessageModel", FullName="Models.MessageModel")

        filterContext.ActionParameters["message"] = serializer.ReadObject(filterContext.HttpContext.Request.InputStream);


    }
}

Upvotes: 7

Views: 4786

Answers (3)

Jason Kleban
Jason Kleban

Reputation: 20788

This post gives this solution (modified) which you'd put on the client with JSON.stringify():

jsonData = JSON.stringify([new Date()], 
    function (k, v) { return this[k] instanceof Date ? '/Date(' + v + ')/' : v; });

Which works in the latest IE, Chrome, and Firefox for me.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

You may try the following function:

public static string FormatDate(DateTime dt)
{
    var serializer = new DataContractJsonSerializer(typeof(DateTime));
    using (var stream = new MemoryStream())
    {
        serializer.WriteObject(stream, dt);
        return Encoding.Default.GetString(stream.ToArray());
    }
} 

And in your view:

var message = 
{
    MessageID: $("#MessageID").val() || 0,
    MessageDate: "/Date(<%= SomeClass.FormatDate(DateTime.Now) %>)/"
};

Upvotes: 2

Mark 909
Mark 909

Reputation: 1835

I had the same problem. What I did was use the following function to convert it to a number

private double GetUnixEpoch(DateTime dateTime)
    {
        var unixTime = dateTime.ToUniversalTime() -
            new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        return unixTime.TotalMilliseconds;
    }

Then you can use that number in the constructor of the Javascript date object to create the date object.

Upvotes: 1

Related Questions