3

如果两个文本框同时验证失败,则 ValidationSummary 显示相同的消息两次。

难道我做错了什么?或者有没有我可以更改的设置来隐藏重复的消息?

 

我将其分解为最简单的示例:

看法:

@model MyModel
@Html.ValidationSummary()
@Html.TextBoxFor(model => model.A)
@Html.TextBoxFor(model => model.B)

模型:

public class MyModel : IValidatableObject
{
    public int A { get; set; }
    public int B { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        //Some logic goes here.        
        yield return new ValidationResult("Validation failed", new[] { "A", "B" });
    }
}

结果:

在此处输入图像描述

4

3 回答 3

9

从 ValidationSummary 的角度来看,它们不是重复的 - 您将模型状态错误分配给字段 A 和 B,因此验证摘要中必须有 2 个错误。它不“知道”它们是相同的。

简单的解决方案:

  • 仅将模型分配给其中之一
  • 从摘要中排除属性分配的错误 - Html.ValidationSummary(true)

更难的解决方案:

  • 制作您自己的 ValidationSummary 助手,在其中调用标准验证摘要逻辑,然后以“选择不同”的方式过滤结果(linq 是您的朋友)。

编辑:

例如这样的东西:

public static class ValidationExtensions
{
    public static MvcHtmlString FilteredValidationSummary(this HtmlHelper html)
    {
        // do some filtering on html.ViewData.ModelState 
        return System.Web.Mvc.Html.ValidationExtensions.ValidationSummary(html);
    }
}
于 2011-10-14T11:42:18.343 回答
2

敲这是你的观点

<ul class="validation-summary-errors">
    @{
        string errorMessage = "", previousError = "";
        foreach (ModelState modelState in (ViewContext.ViewData.ModelState.Values)){

            foreach (ModelError modelError in modelState.Errors)
            {
                errorMessage = modelError.ErrorMessage;
                if (errorMessage != previousError)
                {
                    <li>@modelError.ErrorMessage</li>
                    previousError = modelError.ErrorMessage;
                }                            
            }    
        }
    }
</ul>

您可能可以改进它,因为它仅在 2 个连续错误相同时才有效,如果它使顺序混乱,这可能不起作用,但这会让您开始。我想您可以构建一组错误消息并在每次运行时检查错误,但这种解决方案似乎在大多数情况下都有效。

于 2012-04-24T04:16:47.287 回答
1

ValidationSummary方法返回属性级和模型级错误。如果您不指定任何参数,它只会枚举所有验证消息。

您可以: 1) 对字段 A 和 B 使用不同的消息

// logic here
yield return new ValidationResult("Validation failed for left field", new[] { "A" });
// logic here
yield return new ValidationResult("Validation failed for right field", new[] { "B" });

或者,在您看来

2) 调用 ValidationSummary 并将 excludePropertyErrors 参数设置为 true - ValidationSummary(true)Html.ValidationMessage[For]并在您的每个领域附近拨打电话。

UPDT:...和第三种情况:

在您的模型中添加公共消息(模型级别):

//logic here
yield return new ValidationResult("Validation failed");
yield return new ValidationResult("any text or empty string", new[] { "A", "B" });

在您看来,排除属性消息,但不要为字段添加 ValidationMessage:

@model MyModel
@Html.ValidationSummary(true)
@Html.TextBoxFor(model => model.A)
@Html.TextBoxFor(model => model.B)

所以你会得到一条消息和两个红色框。

于 2011-10-14T11:38:21.177 回答