/// <summary>
 /// Определяет, существует ли в информации о проверке модели данных указанный ключ <paramref name="key"/> и проверяет,
 /// были ли найдены ошибки валидации для данного ключа.
 /// </summary>
 /// <param name="modelState"></param>
 /// <param name="key"></param>
 /// <returns>Возвращает true, если данные формы для ключа <paramref name="key"/> не прошли валидацию.</returns>
 public static bool ContainsKeyError(this ModelStateDictionary modelState, string key)
 {
     if (modelState.ContainsKey(key))
     {
         return(modelState[key].Errors.Count > 0);
     }
     return(false);
 }
Beispiel #2
0
        public static void ParseValidateFor(this ModelStateDictionary modelState, string expressionText)
        {
            ModelErrorCollection errors;

            if ((modelState.ContainsKey(expressionText)) && ((errors = modelState[expressionText].Errors) != null) && (errors.Count > 0))
            {
                foreach (var error in new List <ModelError>(errors))
                {
                    string errorMessage = error.ErrorMessage;
                    if (!errorMessage.StartsWith("JSER:"))
                    {
                        continue;
                    }
                    errors.Remove(error);
                    var serializer = new JavaScriptSerializer();
                    var data       = serializer.DeserializeObject(errorMessage.Substring(5));
                    ApplyValidateValue(modelState, expressionText, data);
                }
            }
        }
        /// <summary>
        /// Validations the summary.
        /// </summary>
        /// <param name="htmlHelper">The HTML helper.</param>
        /// <param name="groupName">Name of the group.</param>
        /// <param name="excludePropertyErrors">if set to <c>true</c> [exclude property errors].</param>
        /// <param name="message">The message.</param>
        /// <param name="htmlAttributes">The HTML attributes.</param>
        /// <returns></returns>
        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string groupName, bool excludePropertyErrors, string message, IDictionary <string, object> htmlAttributes)
        {
            #region Validate Arguments
            if (htmlHelper == null)
            {
                throw new ArgumentNullException("htmlHelper");
            }
            groupName = groupName ?? string.Empty;
            #endregion

            string[] groupNames = groupName.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray();

            if (htmlAttributes == null)
            {
                htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(null);
            }
            htmlAttributes["data-val-valgroup-name"] = groupName;



            object model = htmlHelper.ViewData.Model;
            ModelStateDictionary modelState = htmlHelper.ViewData.ModelState;

            bool canValidate = !modelState.ContainsKey(ValidationGroupsKey) ||
                               (groupNames.Any() && ((IEnumerable <string>)modelState[ValidationGroupsKey].Value.RawValue).Intersect(groupNames).Any()) ||
                               (!groupNames.Any());
            IEnumerable <ModelState> faulted           = canValidate ? GetFaultedModelStates(htmlHelper, groupNames, model) : Enumerable.Empty <ModelState>();
            FormContext formContextForClientValidation = htmlHelper.ViewContext.ClientValidationEnabled ? htmlHelper.ViewContext.FormContext : null;
            if (!canValidate || !faulted.Any())
            {
                if (formContextForClientValidation == null)
                {
                    return(null);
                }
            }
            string str = InitializeResponseString(message);

            IEnumerable <ModelState> values = GetValues(htmlHelper, excludePropertyErrors, modelState, faulted);
            TagBuilder builder3             = AddValidationMessages(htmlHelper, values);
            TagBuilder tagBuilder           = new TagBuilder("div");
            tagBuilder.MergeAttributes <string, object>(htmlAttributes);
            tagBuilder.AddCssClass("validation-summary");
            tagBuilder.AddCssClass(!faulted.Any() ? HtmlHelper.ValidationSummaryValidCssClassName : HtmlHelper.ValidationSummaryCssClassName);
            tagBuilder.InnerHtml = str + builder3.ToString(TagRenderMode.Normal);
            if (formContextForClientValidation != null)
            {
                if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled)
                {
                    if (!excludePropertyErrors)
                    {
                        tagBuilder.MergeAttribute("data-valmsg-summary", "true");
                    }
                }
                else
                {
                    tagBuilder.GenerateId("validationSummary");
                    formContextForClientValidation.ValidationSummaryId      = tagBuilder.Attributes["id"];
                    formContextForClientValidation.ReplaceValidationSummary = !excludePropertyErrors;
                }
            }
            return(new MvcHtmlString(tagBuilder.ToString(TagRenderMode.Normal)));
        }