处理多个错误同一属性

处理多个错误同一属性

本文介绍了ValidationMessage - 处理多个错误同一属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MVC中的控制ValidationMessage。当验证每个属性,它可能有一个以上的错误消息显示,但ValidationMessage仅在列表中显示第一个错误消息。

I'm using ValidationMessage control in MVC. When validating each property, it may have more than one error message to show, but the ValidationMessage only displays the first error message in the list.

下面是一个例子:

ModelState["Key"] = new ModelState();
ModelState["Key"].Errors.Add("Error 1");
ModelState["Key"].Errors.Add("Error 2");

和在HTML我有:<%= Html.ValidationMessage(密钥)%GT;

其中显示:错误1

我想看到页面上的所有错误信息,这将是错误1错误2

I want to see all error messages on the page which will be "Error 1 Error 2"

任何想法,该怎么办呢?

Any idea how to do it?

推荐答案

我有完全相同的问题,所以我创建了一个的HtmlHelper扩展方法为更换为MVC ValidationMessage方法。

I had exactly the same problem, so I created an extension method for HtmlHelper as replacement for the MVC ValidationMessage method.

这种过度的ValidationSummary方法的好处是,它会显示每场的错误信息,因此您可以紧挨着每个字段(同ValidationMessage法)放置。

The benefit of this over ValidationSummary method is that it displays error message per field so you can place it right next to each field (same as ValidationMessage method).

public static string AllValidationMessage(this HtmlHelper helper, string modelName)
{
    StringBuilder builder = new StringBuilder();
    TagBuilder ulTag = new TagBuilder("ul");
    ulTag.AddCssClass("u-error-list");

    builder.Append(ulTag.ToString(TagRenderMode.StartTag));
    if (helper.ViewData.ModelState.ContainsKey(modelName) &&
        helper.ViewData.ModelState[modelName].Errors.Count > 0)
    {
        foreach (var err in helper.ViewData.ModelState[modelName].Errors)
        {
            TagBuilder liTag = new TagBuilder("li") { InnerHtml = HttpUtility.HtmlEncode(err.ErrorMessage) };
            liTag.AddCssClass("u-error-item");
            builder.Append(liTag.ToString());
        }
    }
    builder.Append(ulTag.ToString(TagRenderMode.EndTag));

    var msgSpan = helper.ValidationMessage(modelName, "{placeholder}");

    if (msgSpan == null)
        return string.Empty;

    return msgSpan.ToHtmlString().Replace("{placeholder}", builder.ToString());
}

public static string AllValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
    return HtmlHelperExtensions.AllValidationMessage(helper, ExpressionHelper.GetExpressionText(expression));
}

修改:添加AllValidationMessageFor方法

修改:添加一个空支票msgSpan

Edit: added AllValidationMessageFor method
Edit: added a null check on msgSpan

这篇关于ValidationMessage - 处理多个错误同一属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:26