Reputation: 1397
I have a MVC 3 project that uses Entity Framework. I can successfully update entities like this:
[HttpPost]
publiv RedirectResult Update(MyEntity entity)
{
if(ModelState.IsValid)
{
this.entityRepository.Update(entity);
return RedirectResult(".../Admin");
}
return RedirectResult(".../UnssuccessfullOperation");
}
Now the problem arised when I added DateTime property to my entities. If I do not add the @Html.HiddenFor for my DateTime property the date of my entity is 01.01.0001 (or DateTime.Min), which obviously cannot be saved to the database. If I add the hidden input the date is rendered but on update my ModelState is not valid and I guess this is due to the fact that the datetime is passed as a string.
Now there is one solution, but it seems a little strange - to not render Html.Hidden in the view and to use the datetime from the entityRepository like this:
entity.DateSomething = this.entityRepository.GetSingle(entity.ID).DateSomething;
but it does not seem very correct. Are there any other better options in that case?
Upvotes: 0
Views: 545
Reputation: 1038730
If I add the hidden input the date is rendered but on update my ModelState is not valid and I guess this is due to the fact that the datetime is passed as a string.
No, I suspect that it's due to the culture setting in your application and the datetime format used in the hidden field. They probably don't match.
Take a look at the following blog post which covers the different issues that arise when parsing dates and how the format will depend on whether you are doing a GET or POST request and also a possibility to write a custom model binder to use a fixed format for dates.
Upvotes: 1