Conditionally validating portions of an ASP.NET MVC Model with DataAnnotations?

后端 未结 7 1905
不思量自难忘°
不思量自难忘° 2020-12-30 10:12

I have certain panels on my page that are hidden under certain circumstances.

For instance I might have a \'billing address\' and \'shipping address\' and I dont wan

相关标签:
7条回答
  • 2020-12-30 11:04

    I created a partial model binder that only validates the keys that were submitted. For security reasons (if I was going to take this a step farther) I'd create a data annotation attribute that marks which fields are allowed to be excluded from a model. Then, OnModelUpdated check field attributes to ensure there is no undesired underposting going on.

    public class PartialModelBinder : DefaultModelBinder
    {
        protected override void OnModelUpdated(ControllerContext controllerContext, 
            ModelBindingContext bindingContext)
        {
            // default model binding to get errors
            base.OnModelUpdated(controllerContext, bindingContext);
    
            // remove errors from filds not posted
            // TODO: include request files
            var postedKeys = controllerContext.HttpContext.Request.Form.AllKeys;
            var unpostedKeysWithErrors = bindingContext.ModelState
                .Where(i => !postedKeys.Contains(i.Key))
                .Select(i=> i.Key).ToList();
            foreach (var key in unpostedKeysWithErrors)
            {
                bindingContext.ModelState.Remove(key);
            }
        }    
    }
    
    0 讨论(0)
提交回复
热议问题