How to disable field validation on MVC view?

后端 未结 2 1622
你的背包
你的背包 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条回答
  • 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.

    0 讨论(0)
  • 2021-01-21 19:10

    A good way to solve this is to pass the usermodel id as an adittional field into the remote validation method. This will be blank or null on create but populated on edit. You can then add logic to the remote validation method to check the id.
    See example below

    [Remote("ValidationMethod", "UserModel", AdditionalFields = "Id", ErrorMessage = "Error message")] 
    
    0 讨论(0)
提交回复
热议问题