Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);


    }
}
like image 655
Steven Avatar asked Aug 27 '10 14:08

Steven


1 Answers

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) %>)/"
};
like image 175
Darin Dimitrov Avatar answered Oct 26 '22 12:10

Darin Dimitrov