Manually invoking ModelState validation

后端 未结 4 1504
心在旅途
心在旅途 2020-12-05 22:18

I\'m using ASP.NET MVC 3 code-first and I have added validation data annotations to my models. Here\'s an example model:

public class Product
{
    public i         


        
相关标签:
4条回答
  • 2020-12-05 22:54

    You can call the ValidateModel method within a Controller action (documentation here).

    0 讨论(0)
  • 2020-12-05 23:12

    ValidateModel and TryValidateModel

    You can use ValidateModel or TryValidateModel in controller scope.

    When a model is being validated, all validators for all properties are run if at least one form input is bound to a model property. The ValidateModel is like the method TryValidateModel except that the TryValidateModel method does not throw an InvalidOperationException exception if the model validation fails.

    ValidateModel - throws exception if model is not valid.

    TryValidateModel - returns bool value indicating if model is valid.

    class ValueController : Controller
    {
        public IActionResult Post(MyModel model)
        {
            if (!TryValidateModel(model))
            {
                // Do something
            }
    
            return Ok();
        }
    }
    

    Validate Models one-by-one

    If you validate a list of models one by one, you would want to reset ModelState for each iteration by calling ModelState.Clear().

    Link to the documentation

    0 讨论(0)
  • 2020-12-05 23:14
                //
                var context = new ValidationContext(model);
    
                //If you want to remove some items before validating
                //if (context.Items != null && context.Items.Any())
                //{
                //    context.Items.Remove(context.Items.Where(x => x.Key.ToString() == "Longitude").FirstOrDefault());
                //    context.Items.Remove(context.Items.Where(x => x.Key.ToString() == "Latitude").FirstOrDefault());
                //}
    
                List<ValidationResult> validationResults = new List<ValidationResult>();
                bool isValid = Validator.TryValidateObject(model, context, validationResults, true);
                if (!isValid)
                {
                    //List of errors 
                    //validationResults.Select(r => r.ErrorMessage)
                    //return or do something
                }
    
    0 讨论(0)
  • 2020-12-05 23:17

    I found this to work and do precisely as expected.. showing the ValidationSummary for a freshly retrieved object on a GET action method... prior to any POST

    Me.TryValidateModel(MyCompany.OrderModel)
    
    0 讨论(0)
提交回复
热议问题