コード例 #1
0
        /// <summary>
        /// Validates the given object. If invalid, the errors are added to the ModelState.
        /// </summary>
        /// <param name="objectToValidate">The object to validate</param>
        /// <param name="modelValidator">A specific model validator</param>
        /// <param name="includeProperties">Properties to check</param>
        /// <param name="modelPrefix"></param>
        /// <returns>True if the object is valid</returns>
        protected virtual bool ValidateModel(object objectToValidate, IModelValidator modelValidator, string[] includeProperties, string modelPrefix)
        {
            if (modelValidator == null && this._modelValidator == null)
            {
                throw new InvalidOperationException("A call to Validate() was made while there is no IModelValidator available to perform validation.");
            }
            // if a specific modelvalidator is passed, use that one, otherwise use the modelvalidator of the controller.
            IModelValidator modelValidatorToUse = modelValidator ?? this._modelValidator;

            if (!modelValidatorToUse.IsValid(objectToValidate, includeProperties))
            {
                IDictionary <string, ICollection <string> > errorsForProperties = modelValidatorToUse.GetErrors();
                foreach (KeyValuePair <string, ICollection <string> > errorsForProperty in errorsForProperties)
                {
                    string propertyName = errorsForProperty.Key;
                    if (!String.IsNullOrEmpty(modelPrefix))
                    {
                        propertyName = modelPrefix + "." + propertyName;
                    }
                    foreach (string errorMessage in errorsForProperty.Value)
                    {
                        ViewData.ModelState.AddModelError(propertyName, errorMessage);
                    }
                }
                return(false);
            }
            return(true);
        }
コード例 #2
0
 public ActionResult Index([ModelBinder(typeof(HomeModelBinder))] HomeModel homeModel)
 {
     if (_modelValidator.IsValid(ModelState))
     {
         return(RedirectToAction("Index", "Customer", new { Id = homeModel.AccountNumber }));
     }
     return(View("Index", homeModel));
 }