Reputation: 12990
My ASP.NET MVC view model has datetime properties like:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "yyyyMMdd")]
public DateTime DateOfBirth { get; set; }
My controllers action has:
[HttpPost]
public JsonResult OnCreate(MyViewModel model)
{
}
My properties are do get binded, expect for the datetime properties.
I am entering dates like:
19500125
Which is 1950, Janurary 25th which is what my date format is set to: yyyyMMdd
If I do the following this works:
DateTime dateOfBirth;
if (DateTime.TryParseExact(Request["User.dateOfBirth"], "yyyyMMdd", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateOfBirth))
{
model.User.DateOfBirth = dateOfBirth;
}
But the above is not using the built-in binding and isn't the correct way to do things.
Any clues why the binding for datetime isnt' working?
Upvotes: 2
Views: 1241
Reputation: 54618
Any clues why the binding for datetime isnt' working?
It is working as intended. The default ModelBinder only binds to specific datetime formats. I think the problem is that you are assuming that the DisplayFormatAttribute
has some affect on the ModelBinder. As the attribute states, it is only for Display Format, not for model binding. If you have a custom DateTime format (which you do) then you'll need to write a custom DateTime model binder to bind it.
Upvotes: 4