我有两个自定义绑定器可以绑定.margin-top-20 {
margin-top: 20px;
}
和DateTime
。
我正在DateTime?
中注册它们:
Global.asax
我也尝试过这样:
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ModelBinders.Binders[typeof (DateTime)] = new DateTimeModelBinder();
//ModelBinders.Binders[typeof (DateTime?)] = new NullableDateTimeModelBinder();
//ModelBinders.Binders.Add(typeof (DateTime), new DateTimeModelBinder());
//ModelBinders.Binders.Add(typeof(DateTime?), new NullableDateTimeModelBinder());
}
}
然而,它们永远不会被击中。
模型绑定类在这里(从Internet上窃取):
ModelBinders.Binders.Add(typeof (DateTime), new DateTimeModelBinder());
ModelBinders.Binders.Add(typeof(DateTime?), new NullableDateTimeModelBinder());
在这里:
public class DateTimeModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
DateTime dateTime;
var isDate = DateTime.TryParse(value.AttemptedValue,
Thread.CurrentThread.CurrentUICulture,
DateTimeStyles.None,
out dateTime);
if (!isDate)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName,
$"Cannot bind value {value.AttemptedValue} to a DateTime");
return DateTime.UtcNow;
}
return dateTime;
}
}
我错过了什么?