通常這與在解析模型聯編程序時失敗的非空類型有關。使模型中的日期可以爲空並查看是否可以解決您的問題。否則,編寫你自己的模型綁定器並更好地處理。
編輯:而且按照模型我的意思是視圖的視圖模型,爲了進行建議的更改,如果要在視圖中堅持綁定到您的模型(我假設使用EF),請遵循寫你自己的模型綁定建議
編輯2:我們做了這樣的事情得到一個自定義格式以可空的日期時間來解析(這可能是一個良好的開端,爲您調整爲一個非可空類型):
public sealed class DateTimeBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
if (bindingContext == null)
{
throw new ArgumentNullException("bindingContext");
}
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
if (valueProviderResult == null)
{
return null;
}
var attemptedValue = valueProviderResult.AttemptedValue;
return ParseDateTimeInfo(bindingContext, attemptedValue);
}
private static DateTime? ParseDateTimeInfo(ModelBindingContext bindingContext, string attemptedValue)
{
if (string.IsNullOrEmpty(attemptedValue))
{
return null;
}
if (!Regex.IsMatch(attemptedValue, @"^\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}$", RegexOptions.IgnoreCase))
{
var displayName = bindingContext.ModelMetadata.DisplayName;
var errorMessage = string.Format("{0} must be in the format DD-MMM-YYYY", displayName);
bindingContext.ModelState.AddModelError(bindingContext.ModelMetadata.PropertyName, errorMessage);
return null;
}
return DateTime.Parse(attemptedValue);
}
}
然後註冊此(通過在您的依賴注入容器中提供此類):
public class EventOrganizerProviders : IModelBinderProvider
{
public IModelBinder GetBinder(Type modelType)
{
if (modelType == typeof(DateTime))
{
return new DateTimeBinder();
}
// Other types follow
if (modelType == typeof(TimeSpan?))
{
return new TimeSpanBinder();
}
return null;
}
}
什麼時候沒有錯誤信息?編譯時?表單提交? – Amy 2011-06-06 15:18:57