DavidAndroidDev
DavidAndroidDev

Reputation: 2414

ASP.net MVC - Model with DateTime, trying to serialize for Json() for jqGrid

I've got a model...

    [DataContract]
    public class DeviceModel
    {
        [DataMember(Order=1)]
        public string Alias { get; set; }

        [DataMember(Order = 2)]
        public string Location { get; set; }

        [DataMember(Order = 3)]
        public string State { get; set; }

        [DataMember(Order = 4)]
        public DateTime? DateCreated { get; set; }

        [DataMember(Order = 5)]
        public string RatePlan { get; set; }

        public DeviceModel()
        {
            Alias = null;
            Location = null;
            State = null;
            DateCreated = null;
            RatePlan = null;
        }
    }

This model contains a DateTime object, as you can see. I am using this model as the data for the jqGrid plugin we are using. The only issue is, the DateCreated field shows "/Date(1285128000000)/" when the Grid loads, instead of the readable date. I've read some of the other posts here, but I don't feel that they quite fit the bill for what I'm looking for. I'm looking for a way to format this DateTime field to a human readable string? Suggestions?

Upvotes: 3

Views: 4346

Answers (2)

Todd Smith
Todd Smith

Reputation: 17272

Try Newtonsoft Json.NET as described in this post

Upvotes: 0

Oleg
Oleg

Reputation: 221997

JSON knows only two primitive datatypes: strings and numbers and no Date type. Data Contract Serializer supports more types. For example DateTime, DateTimeOffset, TimeSpan, Guid, Uri, XmlQualifiedName. If you send data to the client which use also Data Contract Serializer to deserialize the data you can use any from the datatypes without any problems.

The most simple solution of your problem is preparing the data on the server before sending the data. If you will serialize only objects which has only strings and numbers as properties or arrays/IList<T> then you will has no problem. For example, per default jqGrid wait the data in the ISO Date format: Y-m-d with numbers for Y, m and d. If you convert your data on the server to the Y-m-d format and use formatter:'date' in the corresponding colModel definition your problem will be solved.

You can also solve the problem on the client side using of the custom formatter and the custom unformatter.

Upvotes: 4

Related Questions