在我们的项目中,我们使用DataAnnotaions进行输入验证。我们的验证员定期实施 IClientValidatable似乎运作良好。
现在我们有一个案例,就是不可能实现IClientValidatable,只能实现服务器验证。
我遇到的问题是默认绑定问题,假设我有文本框,用户应该在此字段中放置dateTime,用户为DateTime设置无效类型,说“23453452345”,在这种情况下默认绑定是无法将值绑定到viewmodel类型typeof(DateTime),并抛出有关该类型不匹配的一般错误或其他内容。而主要的问题是价值用户从文本框输入txtbox消失,因为绑定失败。
因此它打破了常规用户体验,打破了“可访问性”,这对我们公司非常重要。
问题是如何处理这个问题?
答案 0 :(得分:1)
您仍然可以将jquery.validate与自定义规则一起用于客户端验证。对于服务器端,我建议使用字符串字段作为DateTime值,您将尝试在模型绑定器中强制转换为DateTime,如果不正确则会出现验证错误(实际上您可以使用自定义模型绑定器)。因此,在表单验证成功后,你总是会保留错误的值
upd :要实现自定义模型绑定器,您需要执行以下步骤(没有真正检查代码,如果有任何错误,请告诉我):
在global.asax中:
protected void Application_Start()
{
ModelBinders.Binders.Add(typeof(your_model_type), new YourModelTypeBinder());
}
所以现在你需要将YourModelTypeBinder类作为:
public class YourModelTypeBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var model = base.BindModel(controllerContext, bindingContext) as YourModelType;
if (model != null)
{
if (bindingContext.ValueProvider.ContainsPrefix("DateTimeString"))
{
ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(key);
try
{
var s = valueResult.ConvertTo(string);
var valid = DateTime.TryParse(s, out model.RealDateTime);
if (!valid)
bindingContext.ModelState.AddModelError("DateTimeString", "Not a valid date");
}
catch
{
bindingContext.ModelState.AddModelError("DateTimeString", "Not a valid date");
}
}
}
return model;
}
}