您需要設置正確的文化在你的web.config文件的全球化元素,其dd.MM.yyyy
是有效的datetime格式:
<globalization culture="...." uiCulture="...." />
例如這是在德國的默認格式:de-DE
。
UPDATE:
根據要保持應用程序的EN-US區域性,但仍使用不同格式的日期的評論部分您的要求。
using System.Web.Mvc;
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());
但我不想用不同的日期時間格式的英文文化。有什麼解決方法嗎? –
@šljaker,是的。您必須編寫自定義模型聯編程序並使用您喜歡的格式手動分析日期參數。 –
全球化標記是標記的子標記。 –
encc