MVC 3 Razor - Trigger validation from controller

2020-08-19 02:57发布

问题:

I have to check to see if the new users email already exists in the database. The email passes all the normal validation but what if I want to trigger a special validation from the controller if the email already exists after checking it against the database?

回答1:

In controller: ModelState.AddModelError("ErrorEmail", "Error Message");

In View: @Html.ValidationMessage("ErrorEmail")

Hope this helps



回答2:

I think what you are looking for is the RemoteAttribute.

This is a ValidationAttribute for remote validation. It works like the other validation attributes by adding model errors to your modelstate dictionary.

Check out these articles on using the RemoteAttribute:

  • http://deanhume.com/Home/BlogPost/mvc-3-and-remote-validation/51
  • http://davidhayden.com/blog/dave/archive/2011/01/04/ASPNETMVC3RemoteValidationTutorial.aspx


回答3:

I found a way to perform conditional validation from the ViewModel. The VM class will need to implement the IValidatableObject interface.

Then add a method similar to this at the bottom of the VM:

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (validationContext == null)
            return null;

        var valResults = new List<ValidationResult>();

        if (!EmailExists))
            valResults.Add(new ValidationResult($"Email is required.", new[] { "ErrorEmail" }));

        return valResults;
    }

And of course you will need this in the View:

@Html.ValidationMessage("ErrorEmail")

Hope that helps!