Ahhhh, now it is clear. You seem to have problems binding back the value. Not with displaying it on the view. Indeed, that's the fault of the default model binder. You could write and use a custom one that will take into consideration the [DisplayFormat]
attribute on your model. I have illustrated such a custom model binder here: https://stackoverflow.com/a/7836093/29407
Apparently some problems still persist. Here's my full setup working perfectly fine on both ASP.NET MVC 3 & 4 RC.
Model:
public class MyViewModel
{
[DisplayName("date of birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Birth { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
Birth = DateTime.Now
});
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
View:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.LabelFor(x => x.Birth)
@Html.EditorFor(x => x.Birth)
@Html.ValidationMessageFor(x => x.Birth)
<button type="submit">OK</button>
}
Registration of the custom model binder in Application_Start
:
ModelBinders.Binders.Add(typeof(DateTime?), new MyDateTimeModelBinder());
And the custom model binder itself:
public class MyDateTimeModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
// use the format specified in the DisplayFormat attribute to parse the date
if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
Now, no matter what culture you have setup in your web.config (<globalization>
element) or the current thread culture, the custom model binder will use the DisplayFormat
attribute's date format when parsing nullable dates.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…