ASP.NET MVC3 - DateTime格式 [英] ASP.NET MVC3 - DateTime format
问题描述
我使用ASP.NET MVC 3结果
我的视图模型看起来是这样的:
I'm using ASP.NET MVC 3.
My ViewModel looks like this:
public class Foo
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
...
}
在看,我有这样的事情:
In view, I have something like this:
<div class="editor-field">
@Html.EditorFor(model => model.StartDate)
<br />
@Html.ValidationMessageFor(model => model.StartDate)
</div>
开始日期显示为正确的格式,但是当我改变它的价值,2011年11月19日和提交表单,我收到以下错误信息:值'19 .11.2011'是无效的起始日期
StartDate is displayed in correct format, but when I change it's value to 19.11.2011 and submit the form, I get the following error message: "The value '19.11.2011' is not valid for StartDate."
任何帮助将大大AP preciated!
Any help would be greatly appreciated!
推荐答案
您需要设置正确的文化在你的web.config文件的全球化元素而 DD.MM.YYYY
是一个有效的日期时间格式:
You need to set the proper culture in the globalization element of your web.config file for which dd.MM.yyyy
is a valid datetime format:
<globalization culture="...." uiCulture="...." />
例如这是默认的格式,在德国:去DE
For example that's the default format in german: de-DE
.
更新:
根据你要保持应用程序的EN-US区域性,但仍使用不同格式的日期的评论部分您的要求。这可以通过编写自定义模型绑定来实现:
According to your requirement in the comments section you want to keep en-US culture of the application but still use a different formats for the dates. This could be achieved by writing a custom model binder:
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);
}
}
您将在注册的Application_Start
:
ModelBinders.Binders.Add(typeof(DateTime), new MyDateTimeModelBinder());
这篇关于ASP.NET MVC3 - DateTime格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!