通常这与在解析模型联编程序时失败的非空类型有关。使模型中的日期可以为空并查看是否可以解决您的问题。否则,编写你自己的模型绑定器并更好地处理。
编辑:而且按照模型我的意思是视图的视图模型,为了进行建议的更改,如果要在视图中坚持绑定到您的模型(我假设使用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