I'm having an issue using the DisplayFormat attribute on a Datetime property during the postback validation.
To be clear this is not a main issue but I would like to understand a way to make it works without a 'hack' or simply discuss about this point (in the case that's a 'normal' behavior).
Let's admit that I have some datetimes in DB (eg. 10/17/2014 12:00:00 AM) to display in a form. I'm using the DataType(Datatype.Date)
and DisplayFormat(...)
attributes but when I post back my form I got the ModelState to be invalid due to Datetime format.
--MyModel class file (.cs)
namespace Package.To.Models {
public class MyModel
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0: dd/MM/yyyy}", ApplyFormatInEditMode = true]
public Datetime myDate { get; set; }
...other properties
}
}
--cshtml file
@model Package.To.Models.MyModel
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.myDate)
</div>
<div class="editor-field">
<!-- displayed with the good format eg. 17/10/2014 -->
@Html.EditorFor(model => model.myDate)
</div>
<input type="submit" value="Ok" class="button"/>
</fieldset>
}
--controller file (.cs)
[HttpPost]
public ActionResult calledWhenSubmit(MyModel model)
{
// invalid model.myDate: 1/1/0001 12:00:00 AM
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToArray();
// errors.Errors[0].ErrorMessage: "The value '17/10/2014' is not valid for myDate"
// errors.Errors[0].Exception._COMPlusExceptionCode: -532462766
if (ModelState.IsValid) // returning false
{
...some code
}
return View();
}
It appears that if I delete the DisplayFormat(...)
attribute everything works fine (except the fact that the displayed date is in the wrong format in the form).
I found a lot of posts about Datetime and ModelState issues on SO but nothing in a config as simply as I got so I'm all ears about what I'm missing
I had the same problem. Although you set the
DateFormatString
but the controller validation does not understand this format, it understands the culture format. You need to change it inStartup.cs
ConfigureServices method by adding the following code: