Manually invoking ModelState validation

后端 未结 4 1521
心在旅途
心在旅途 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 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 validationResults = new List();
                bool isValid = Validator.TryValidateObject(model, context, validationResults, true);
                if (!isValid)
                {
                    //List of errors 
                    //validationResults.Select(r => r.ErrorMessage)
                    //return or do something
                }
    

提交回复
热议问题