我得到了答案我使用的自定義ModelBinder的,爲了解決這個問題,
首先,我註冊的這條線在Application_Start方法在Global.asax中:
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);
}
}
感謝Darin Dimitrov的answer!
嘗試使用數據類型:[DataType(DataType.Date)] – crunchy
請創建一個[MCVE](http://stackoverflow.com/help/mcve)。 –
假設你的服務器文化是接受'dd/MM/yyyy'中的日期的文化,那麼問題是'jquery.validate',它驗證'MM/dd/yyyy'格式的日期。你還沒有表明,如果你使用日期選擇器,但參考[這個答案](http://stackoverflow.com/questions/27285458/jquery-ui-date-picker-and-mvc-view-model-type-datetime/27286969#27286969 )一些選項 –