public static string GetError(this System.Web.Mvc.ModelStateDictionary state) { string error = string.Empty; foreach (var ms in state.Values) { foreach (var e in ms.Errors) { if (!string.IsNullOrWhiteSpace(e.ErrorMessage)) { error = string.Concat(error, e.ErrorMessage, ";"); } else if (e.Exception != null) { var exp = e.Exception; if (exp is JsonReaderException) { error = string.Concat(error, "wrong json format!!"); } else { error = string.Concat(error, e.Exception.Message, ";"); } } } } return(error); }
/// <summary> /// Excludes the list of model properties from model validation. /// </summary> /// <param name="modelState">The model state dictionary which holds the state of model data being interpreted.</param> /// <param name="modelProperties">A string array of delimited string property names of the model to be excluded from the model state validation.</param> public static void Remove(this System.Web.Mvc.ModelStateDictionary modelState, params string[] modelProperties) { foreach (var prop in modelProperties) { modelState.Remove(prop); } }
public void SetModelStateError(System.Web.Mvc.ModelStateDictionary modelState) { if (!string.IsNullOrEmpty(error)) { modelState.AddModelError("error", error); } }
public AjaxResult(System.Web.Mvc.ModelStateDictionary modelState, int id) { Result = modelState.IsValid; ErrorId = id; Errors = modelState.Where(kvp => kvp.Value.Errors.Count > 0).ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()).ToArray(); }
internal static string ParseErrors(System.Web.Mvc.ModelStateDictionary ModelState) { StringBuilder errors = new StringBuilder(); foreach (var value in ModelState.Values) { if (value.Errors.Count > 0) { foreach (var error in value.Errors) { if (string.IsNullOrEmpty(error.ErrorMessage)) { Exception innerException = error.Exception; while (innerException != null) { errors.AppendLine(innerException.Message); innerException = innerException.InnerException; } } else { errors.AppendLine(error.ErrorMessage); } } } } errors.AppendLine(Resources.Messages.SaveFailed); return(errors.ToString()); }
public static IEnumerable <string> GetErrors(this System.Web.Mvc.ModelStateDictionary modelState) { //return modelState.Values.SelectMany(v => v.Errors) // .Select(v => v.ErrorMessage + " " + v.Exception).ToList(); var errorsList = modelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage /* + " " + x.Exception*/); return(errorsList); }
public AjaxResult(System.Web.Mvc.ModelStateDictionary modelState, int id, string customErrorMessage) { Result = false; CustomErrorMessage = customErrorMessage; ErrorId = id; Errors = modelState.Where(kvp => kvp.Value.Errors.Count > 0).ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()).ToArray(); }
public static string GetErrors(this System.Web.Mvc.ModelStateDictionary modalState) { var errorsSb = new StringBuilder(); var errors = modalState.Values.SelectMany(x => x.Errors.Select(y => y.ErrorMessage)).ToList(); errors.ForEach(x => errorsSb.AppendLine(x)); return(errorsSb.ToString()); }
public void GetCurrState(string currPrefix, int updateIndex, System.Web.Mvc.ModelStateDictionary modelState) { if (currPrefix == "display") { currPrefix = string.Empty; } this.prefix = currPrefix; this.modelState = modelState; }
public static bool CheckIfHasErrorsFor <TModel>(this System.Web.Mvc.ModelStateDictionary modelState, Expression <Func <TModel, object> > expression) { string expressionText = Helpers.GetExpressionText(expression); return(!string.IsNullOrEmpty(expressionText) && modelState.Where(item => item.Key.StartsWith(expressionText)) .Any(item => item.Value.Errors.Count != 0)); }
public void Validate(System.Web.Mvc.ModelStateDictionary modelState) { ValidationCheck.CheckErrors(this, modelState); //check Login if (!ValidationCheck.IsEmpty(this.Login) && !ProjectConfig.Config.DataProvider.GetInstance().UserRepository.ValidateLogin(this.Login, ID)) { modelState.AddModelError("Login", "This login already present in system"); } //check Email if (!ValidationCheck.IsEmpty(this.Email) && !ProjectConfig.Config.DataProvider.GetInstance().UserRepository.ValidateEmail(this.Email, ID)) { modelState.AddModelError("Email", "This email already present in system"); } if (!String.Equals(this.Password, this.ConfirmPassword, StringComparison.Ordinal)) { modelState.AddModelError("Password", "The password and confirmation password do not match."); modelState.AddModelError("ConfirmPassword", ""); } if (!String.Equals(this.Email, this.ConfirmEmail, StringComparison.Ordinal)) { modelState.AddModelError("Email", "The email and confirmation email do not match."); modelState.AddModelError("ConfirmEmail", ""); } if (this.BillingState == "--" && this.BillingCountry == 1) { modelState.AddModelError("BillingState", "'State' is required"); } if (this.ShippingState == "--" && this.ShippingCountry == 1 && !this.BillingLikeShipping) { modelState.AddModelError("ShippingState", "'State' is required"); } if (this.BillingState != "--" && this.BillingCountry > 1) { modelState.AddModelError("BillingState", "'State' must have value '--'"); } if (this.ShippingState != "--" && this.ShippingCountry > 1 && !this.BillingLikeShipping) { modelState.AddModelError("ShippingState", "'State' must have value '--'"); } if (this.BillingState == "--" && this.BillingCountry > 1 && String.IsNullOrEmpty(this.BillingInternationalState)) { modelState.AddModelError("BillingInternationalState", "'International State' is required"); } if (this.ShippingState == "--" && this.ShippingCountry > 1 && String.IsNullOrEmpty(this.ShippingInternationalState) && !this.BillingLikeShipping) { modelState.AddModelError("ShippingInternationalState", "'International State' is required"); } }
public virtual void CopyErrorsToModelState(System.Web.Mvc.ModelStateDictionary ModelState) { if (Errors.Any()) { foreach (var err in Errors) { ModelState.AddModelError(err.PropertyName, err.ErrorMessage); } } }
public static void CopyToModelState(this RuleException re, System.Web.Mvc.ModelStateDictionary modelState, string prefix) { foreach (string key in re.Errors) { foreach (string value in re.Errors.GetValues(key)) { modelState.AddModelError(prefix + "." + key, value); } } }
public static void ClearErrorsFor <TModel>(this System.Web.Mvc.ModelStateDictionary modelState, Expression <Func <TModel, object> > modelExpression) { string expressionText = Helpers.GetExpressionText(modelExpression); if (!string.IsNullOrEmpty(expressionText)) { modelState.Where(item => item.Key.Contains(expressionText)) .ToList() .ForEach(item => item.Value.Errors.Clear()); } }
public static List <string> GetErrorListFromModelStateMvc( System.Web.Mvc.ModelStateDictionary modelState ) { var query = from state in modelState.Values from error in state.Errors select error.ErrorMessage; var errorList = query.ToList(); return(errorList); }
public static bool Validate <TModel, TValidator>(TModel model, TValidator validator, System.Web.Mvc.ModelStateDictionary modelState) where TValidator : AbstractValidator <TModel> { ValidationResult result = validator.Validate(model); foreach (var error in result.Errors) { modelState.AddModelError(error.PropertyName, error.ErrorMessage); } return(result.IsValid); }
public static void AddModelErrors(this ModelStateDictionary modelState, IEnumerable <ValidationResult> validationResults, string defaultErrorKey = null) { if (validationResults == null) { return; } foreach (var validationResult in validationResults) { var key = validationResult.MemberNames.FirstOrDefault() ?? defaultErrorKey ?? string.Empty; modelState.AddModelError(key, validationResult.ErrorMessage); } }
private ModelStateDictionary ConvertToModelState(System.Web.Mvc.ModelStateDictionary state) { ModelStateDictionary ret = new ModelStateDictionary(); foreach (var list in state.ToList()) { for (int i = 0; i < list.Value.Errors.Count; i++) { ret.AddModelError(list.Key, list.Value.Errors[i].ErrorMessage); } } return(ret); }
private static IEnumerable <string> ErrorMessages(System.Web.Mvc.ModelStateDictionary modelState) { foreach (var kp in modelState) { foreach (var e in kp.Value.Errors) { if (!String.IsNullOrEmpty(e.ErrorMessage)) { yield return(e.ErrorMessage); } } } }
public void ExtractErrors(System.Web.Mvc.ModelStateDictionary modelState) { //the dictionary has the name of the attribute as key and the number of errors as value Dictionary <string, int> errorList = modelState .ToDictionary( kvp => kvp.Key, kvp => kvp.Value.Errors.Count ); //Serialize the dictionary and save it in the ErrorsList attribute of the Model. //The attribute will be rendered in the view in a input hidden tag. this.ErrorsList = JsonConvert.SerializeObject(errorList, Formatting.Indented); }
public static void ClearErrorsFor <TModel, TException>(this System.Web.Mvc.ModelStateDictionary modelState, Expression <Func <TModel, object> > modelExpression) { string expressionText = Helpers.GetExpressionText(modelExpression); if (!string.IsNullOrEmpty(expressionText)) { modelState.Where(item => item.Key.Contains(expressionText)) .ToList() .ForEach(item => item.Value.Errors.Where(e => e.Exception != null && e.Exception.GetType() == typeof(TException)) .ToList() .ForEach(e => item.Value.Errors.Remove(e))); } }
/// <summary> /// Returns true when a model state validation error is found for the property provided /// </summary> /// <typeparam name="TModel">Model type to search</typeparam> /// <typeparam name="TProp">Property type searching</typeparam> /// <param name="expression">Property to search for</param> /// <returns></returns> public static bool HasErrorForProperty <TModel, TProp>(this System.Web.Mvc.ModelStateDictionary modelState, Expression <Func <TModel, TProp> > expression) { var memberExpression = expression.Body as MemberExpression; for (int i = 0; i < modelState.Keys.Count; i++) { if (modelState.Keys.ElementAt(i).Equals(memberExpression.Member.Name)) { return(modelState.Values.ElementAt(i).Errors.Count > 0); } } return(false); }
/// <summary> /// MVC返回验证信息 /// </summary> /// <param name="dictionary"></param> /// <returns></returns> public static string GetErrorMessage(this System.Web.Mvc.ModelStateDictionary dictionary) { string errorMsg = string.Empty; foreach (var item in dictionary.Values) { if (item.Errors != null && item.Errors.Count > 0) { errorMsg = item.Errors[0].ErrorMessage; break; } } return(errorMsg); }
public void GetCurrState(string currPrefix, int updateIndex, System.Web.Mvc.ModelStateDictionary modelState) { this.currPrefix = currPrefix; this.updateIndex = updateIndex; this.modelState = modelState; startPrefix = ".$$"; if (!string.IsNullOrWhiteSpace(currPrefix) && currPrefix != "updatemodel") { startPrefix = currPrefix + startPrefix; } if (startPrefix[0] == '.') { startPrefix = startPrefix.Substring(1); } }
/// <inheritDoc/> public virtual string GetErrorFromViewModel(System.Web.Mvc.ModelStateDictionary modelStateDict) { var firstErrorValue = modelStateDict.Values.FirstOrDefault(v => v.Errors.Any()); if (firstErrorValue != null) { var firstError = firstErrorValue.Errors.FirstOrDefault(); if (firstError != null) { return(firstError.ErrorMessage); } } return(null); }
/// <summary> /// ╗ых├┤ь╬зл┼¤б /// </summary> /// <param name="modelState"></param> /// <returns></returns> public static string GetErrorMsg(this System.Web.Mvc.ModelStateDictionary modelState) { if (modelState.IsValid || !modelState.Values.Any()) { return(string.Empty); } foreach (var m in modelState.Values) { if (m.Errors.Any()) { return(m.Errors[0].ErrorMessage); } } return(string.Empty); }
/// <summary> /// MVC form validation messages for Angular /// </summary> /// <param name="modelState"></param> /// <returns></returns> public static IEnumerable <FormResponseFieldErrors> GetErrors(this System.Web.Mvc.ModelStateDictionary modelState) { List <FormResponseFieldErrors> errors = new List <FormResponseFieldErrors>(); foreach (var fieldErrors in modelState.Where(x => x.Value.Errors.Any()).Select(x => new { x.Key, x.Value.Errors })) { errors.Add( new FormResponseFieldErrors() { Field = fieldErrors.Key, ErrorMessages = fieldErrors.Errors.Select(x => x.ErrorMessage) }); } return(errors); }
/// <summary> /// 获取所有错误信息 /// </summary> /// <param name="modelStateDictionary">所要扩展的对象</param> /// <param name="separator">分隔符</param> /// <returns>错误列表</returns> public static string ExpendErrors(this System.Web.Mvc.ModelStateDictionary modelStateDictionary, string separator) { var sbErrors = new System.Text.StringBuilder(); foreach (var item in modelStateDictionary.Values) { if (item.Errors.Count > 0) { for (var i = item.Errors.Count - 1; i >= 0; i--) { sbErrors.Append(item.Errors[i].ErrorMessage); sbErrors.Append(separator); } } } return(sbErrors.ToString()); }
/// <inheritDoc/> public virtual void ValidateProfileData(ProfileEditViewModel viewModel, System.Web.Mvc.ModelStateDictionary modelState) { List <ProfileBindingsContract> profileBindingsList = this.GetDeserializedProfileBindings(); foreach (var profile in this.SelectedUserProfiles) { var readOnlyFields = string.IsNullOrEmpty(profile.User.ExternalProviderName) ? new string[0] : UserManager.GetReadOnlyFields(profile.GetType().Name, profile.User.ExternalProviderName); var profileBindings = profileBindingsList.SingleOrDefault(p => p.ProfileType == profile.GetType().FullName); if (profileBindings != null) { var requiredProperties = profileBindings.Properties.Where(p => p.Required); foreach (var prop in requiredProperties) { if (readOnlyFields.Any(x => x.Equals(prop.Name, StringComparison.OrdinalIgnoreCase))) { // skip validation for read-only fields continue; } string propValue; if (!viewModel.Profile.TryGetValue(prop.Name, out propValue) || string.IsNullOrWhiteSpace(propValue)) { modelState.AddModelError(string.Format("Profile[{0}]", prop.Name), string.Format(Res.Get <ProfileResources>().RequiredProfileField, prop.Name)); } } } } var minPassLength = UserManager.GetManager(this.MembershipProvider).MinRequiredPasswordLength; if (!string.IsNullOrEmpty(viewModel.OldPassword) && !string.IsNullOrEmpty(viewModel.NewPassword) && !string.IsNullOrEmpty(viewModel.RepeatPassword)) { if (viewModel.NewPassword.Length < minPassLength) { modelState.AddModelError("NewPassword", string.Format(Res.Get <ProfileResources>().MinimumPasswordLength, minPassLength)); } if (viewModel.RepeatPassword.Length < minPassLength) { modelState.AddModelError("RepeatPassword", string.Format(Res.Get <ProfileResources>().MinimumPasswordLength, minPassLength)); } } }
public string GetValidationErrors(System.Web.Mvc.ModelStateDictionary ModelState) { string ErrorMessage = ""; if (ModelState.Values.Count > 0) { ErrorMessage = "<ul>"; foreach (System.Web.Mvc.ModelState modelState in ModelState.Values) { foreach (System.Web.Mvc.ModelError error in modelState.Errors) { ErrorMessage = ErrorMessage + "<li>" + error.ErrorMessage + " </li> "; } } ErrorMessage = ErrorMessage + "</ul>"; } return(ErrorMessage); }