I am using Angular JS to get and post data to my MVC 4 controller as JSON. All of my properties convert properly except the DateTime/DateTime? types. I would like to have a 'set it and forget it' approach to handling dates so that new classes and or properties that are added will not have to remember to do some special conversion to handle a date properly. I have seen the following approaches and possible disadvantages. What approach are people out there using for the same platform? Is there something in MVC4 that is handling this properly that I may not have configured? Any suggestions will be greatly appreciated.
Please see the following code example. C# class:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public DateTime? ApprovedForSomething { get; set; }
}
Angular JS Controller:
function PersonController($scope, $http) {
$scope.getPerson = function () {
$http.get('../../Home/GetPerson/1').success(function (data) {
$scope.Person = data;
});
}
$scope.updateApprovedForSomething = function () {
$http.post('../../Home/UpdatePerson', { person: $scope.Person }).success(function (data) {
console.log(data);
});
}
}
Fiddlers POST:
HTTP/1.1 200 OK Cache-Control: private Content-Type: application/json; charset=utf-8 Server: Microsoft-IIS/8.0 X-AspNetMvc-Version: 4.0 X-AspNet-Version: 4.0.30319 X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNcbmlja1xkb2N1bWVudHNcdmlzdWFsIHN0dWRpbyAyMDEyXFByb2plY3RzXFZhbGlkYXRpb25UZXN0XEhvbWVcR2V0UGVyc29uXDE=?= X-Powered-By: ASP.NET Date: Wed, 16 Jan 2013 14:48:34 GMT Content-Length: 124
{"FirstName":"Bob","LastName":"Smith","BirthDate":"/Date(695573315098)/","ApprovedForSomething":"/Date(1358261315098)/"}
As you can see with the Fiddler data the date is coming over as a JSON date but when hitting the POST method the DateTime property is not correct and the DateTime? property is null.
Do you have the option of switching your AJAX postback to be handled by a WebApi's ApiController
instead of an MVC controller?
I ran into this problem recently and took advantage of the ApiController's support for ISO 8601 date format.
Here's some info: http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With