Reputation: 568
I Have a model which has DateTime type in it:
public class ToDo
{
public int id { get; set; }
public int parentId { get; set; }
public string note { get; set; }
public DateTime due { get; set; }
public ToDo(int id, int parentId, string note, DateTime due)
{
this.id = id;
this.parentId = parentId;
this.note = note;
this.due = due;
}
}
I've created a controller for this class to send my post requests through api. but I don't know how to bind DateTime type to json i've tried a request with the following body but it didn't work out:
{"parentId":1,"note":"hello world","due":{"year":2017,"month": 11,"day":25}}
How should I post the DateTime type?
Upvotes: 6
Views: 23634
Reputation: 29976
For DateTime
Type property, you need to pass the String which could be converted to DateTime
Type.
For {"year":2017,"month": 11,"day":25}
, it is object instead of String, it will fail to convert to DateTime.
For anything which could be converted to DateTime
by Convert.ToDateTime
and DateTime.Parse
.
So, both {"parentId":1,"note":"hello world","due":"05/05/2005"}
and {"parentId":1,"note":"hello world","due":"2018-05-10"}
will work, you could make test with the DateTime string you need.
Upvotes: 3
Reputation: 568
Apparently one of the ways you can do it is this:
{"due": "2017-11-01T00:00:00"}
it was actually an easy question but if you want to make sure how to make a proper post request for unknown object types format it's best to send an object with empty body to see the default values.
Upvotes: 14