sl3*_*dg3 5 c# asp.net-mvc-3 asp.net-mvc-2
我编写了一个自定义模型绑定器,它应该根据当前文化来映射来自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
}
Run Code Online (Sandbox Code Playgroud)
我在global.asax中注册了模型绑定器:
ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeModelBinder());
Run Code Online (Sandbox Code Playgroud)
现在问题发生在最后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);
}
}
Run Code Online (Sandbox Code Playgroud)
好吧,这实际上是一个微不足道的解决方案:我创建一个默认绑定器的新实例并将任务传递给他:
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
}
Run Code Online (Sandbox Code Playgroud)