Androme
Androme

Reputation: 2449

JSON date to Model C# DateTime

I have a ASP.NET MVC API site, where one of my models require a DateTime, but no matter what i do, it won't accept the data i send it as a valid model!

I have tryed

{"Owner":"s083151","Permissions":"public","Name":"SomeRandomMeeting","Begin":"2013-03-28T13:00:00.2124557+01:00","End":"2013-03-28T17:00:00.2124557+01:00","Url":"MyRandomUrl"}

and

{"Owner":"s083151","Permissions":"public","Name":"SomeRandomMeeting","Begin":Date(1364234400),"End":Date(1364248800),"Url":"MyRandomUrl"}

and

{"Owner":"s083151","Permissions":"public","Name":"SomeRandomMeeting","Begin":1364234400,"End":1364248800,"Url":"MyRandomUrl"}

and

{"Owner":"s083151","Permissions":"public","Name":"SomeRandomMeeting","Begin":"1364234400","End":"1364248800","Url":"MyRandomUrl"}

But none of it, is accepted as Model.IsValid, what am i doing wrong?

I use fiddler to test the requests here are my Request headers

User-Agent: Fiddler
Content-Type: application/json

The data model

[DataContract]
public class MeetingModel
{
    [Required]
    [StringLength(500)]
    public string Owner { get; set; }

    [Required]
    public string Permissions { get; set; }

    [Required]
    [StringLength(500)]
    public string Name { get; set; }

    [Required]
    public DateTime Begin { get; set; }

    [Required]
    public DateTime End { get; set; }

    [Required]
    [StringLength(75)]
    public string Url { get; set; }

    public string MeetingId { get; set; }

    public TimeSpan Duration { get; set; }

    public List<UserModel> Hosts { get; set; }

    public List<UserModel> Participants { get; set; }
}

Upvotes: 0

Views: 2266

Answers (2)

Alex Tsvetkov
Alex Tsvetkov

Reputation: 1659

Seems that it is not because of the date, but rather because of the typo: you have Permissions (plural) property in your class, but Permission (singular) in JSON.

As for date formats, Scott Hanselman had a post about that, from which it looks like the format that the default JSON model binder will understand looks like "2013-03-21T00:00:00" (and seems to be a part of ISO 8601 standard).

Upvotes: 1

Agustin Meriles
Agustin Meriles

Reputation: 4854

Putting the date field like this, between slashes, worked for me:

{"Owner":"s083151",
 "Permissions":"public",
 "Name":"SomeRandomMeeting",
 "Begin":"/Date(1364234400)/",
 "End":"/Date(1364248800)/",
 "Url":"MyRandomUrl"}

If you are generating the JSON with C# code, be careful to add the scape backslash:

"\/Date(1364234400)\/"

Upvotes: 3

Related Questions