我在ASP.NET MVC 2中使用自定义模型绑定器,如下所示:
public override object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext) { if (controllerContext == null) { throw new ArgumentNullException("controllerContext"); } if (bindingContext == null) { throw new ArgumentNullException("bindingContext"); } BaseContentObject obj = (BaseContentObject)base.BindModel(controllerContext,bindingContext); if(string.IsNullOrWhiteSpace(obj.Slug)) { // creating new object obj.Created = obj.Modified = DateTime.Now; obj.ModifiedBy = obj.CreatedBy = controllerContext.HttpContext.User.Identity.Name; // slug is not provided thru UI,derivate it from Title; property setter removes chars that are not allowed obj.Slug = obj.Title; ModelStateDictionary modelStateDictionary = bindingContext.ModelState; modelStateDictionary.SetModelValue("Slug",new ValueProviderResult(obj.Slug,obj.Slug,null)); ...
当我从这个绑定器返回到控制器操作时,我作为操作参数提供的业务对象被正确更改(行obj.Created = …. work).
但是,ModelState不会更新.我知道这是因为我在业务对象的Slug属性上有必需,虽然我在自定义模型绑定器中修改了ModelStateDictionary,为它提供了一个Slug(如上所示),但ModelState.IsValid仍然是假的.
如果我在调试会话的Watch窗口中放入ModelState [“Slug”],它会说它有错误(1),所以显然它是空的,因此失败了.
解决方法
显然,一旦更改了某个键的值,就无法重新验证ModelState. IsValid仍然为false,因为为某个键设置新值不会触发重新验证.
解决方案是首先删除触发IsValid为false的密钥并重新创建它并为其分配值.当你这样做时,ModelState会自动重新生效,如果一切正常,则IsValid返回true.
喜欢这个:
bindingContext.ModelState.Remove("Slug"); bindingContext.ModelState.Add("Slug",new ModelState()); bindingContext.ModelState.SetModelValue("Slug",null));