从自定义模型活页夹调用默认模型活页夹?

我编写了一个自定义模型绑定器,它应该根据当前的文化来映射来自URL-Strings(GET)的日期(这里的旁注:如果你使用GET作为http-call,默认的模型绑定器不会考虑当前的文化…)。

public class DateTimeModelBinder : IModelBinder { #region IModelBinder Members public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (controllerContext.HttpContext.Request.HttpMethod == "GET") { string theDate = controllerContext.HttpContext.Request.Form[bindingContext.ModelName]; DateTime dt = new DateTime(); bool success = DateTime.TryParse(theDate, System.Globalization.CultureInfo.CurrentUICulture, System.Globalization.DateTimeStyles.None, out dt); if (success) { return dt; } else { return null; } } return null; // Oooops... } #endregion } 

我在global.asax中注册了模型绑定器:

 ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeModelBinder()); 

现在问题发生在最后一次return null; 。 如果我使用POST的其他表单,它将用null覆盖已映射的值。 我怎么能避免这个?

任何输入的Thx。 sl3dg3

DefaultModelBinder派生,然后调用基本方法:

 public class DateTimeModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { // ... Your code here return base.BindModel(controllerContext, bindingContext); } } 

嗯,这实际上是一个简单的解决方案:我创建一个默认绑定器的新实例并将任务传递给他:

 public class DateTimeModelBinder : IModelBinder { #region IModelBinder Members public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (controllerContext.HttpContext.Request.HttpMethod == "GET") { string theDate = controllerContext.HttpContext.Request.Form[bindingContext.ModelName]; DateTime dt = new DateTime(); bool success = DateTime.TryParse(theDate, System.Globalization.CultureInfo.CurrentUICulture, System.Globalization.DateTimeStyles.None, out dt); if (success) { return dt; } else { return null; } } DefaultModelBinder binder = new DefaultModelBinder(); return binder.BindModel(controllerContext, bindingContext); } #endregion }