啊啊啊,现在清楚了。您似乎在绑定值时遇到问题。不是在视图上显示它。事实上,这是默认模型绑定器的错误。您可以编写并使用一个自定义的,它将考虑[DisplayFormat]
您模型上的属性。我在这里说明了这样一个自定义模型绑定器:https ://stackoverflow.com/a/7836093/29407
显然有些问题仍然存在。这是我在 ASP.NET MVC 3 和 4 RC 上的完整设置。
模型:
public class MyViewModel
{
[DisplayName("date of birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Birth { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
Birth = DateTime.Now
});
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
看法:
@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>
}
自定义模型绑定器的注册Application_Start
:
ModelBinders.Binders.Add(typeof(DateTime?), new MyDateTimeModelBinder());
以及自定义模型绑定器本身:
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);
}
}
现在,无论您在 web.config (<globalization>
元素) 中设置了什么文化或当前线程文化,自定义模型绑定器DisplayFormat
在解析可空日期时都将使用属性的日期格式。