How to disable field validation on MVC view?

后端 未结 2 1623
你的背包
你的背包 2021-01-21 18:30

I have an MVC 3 application. I have a model called UserModel that contains an email field, validated for unique with RemoteAttribute. I want to use UserModel on 2 Views - EditU

2条回答
  •  梦毁少年i
    2021-01-21 19:04

    You can use the partial validation technique to modify the validation results. This example will discard any errors for the Email field.

    public class DontValidateEmailAttribute : ActionFilterAttribute {
    
      public override void OnActionExecuting(ActionExecutingContext filterContext) {
        var modelState = filterContext.Controller.ViewData.ModelState; 
        var incomingValues = filterContext.Controller.ValueProvider;
    
        var key = modelState.Keys.Single(x => incomingValues.Equals("Email"));    
        modelState[key].Errors.Clear();
    
      }
    }
    

    and apply this attribute to your Edit Controller.

    I learnt this technique from Steve Sanderson's Pro ASP NET MVC 3. He uses the technique to validate a model that has required fields but the data entry is a multistep wizard. If the value has not been returned in the form post, he removes the errors for that property.

提交回复
热议问题