创建返回多个错误消息的自定义 ValidationAttribute 类

use*_*075 5 c# asp.net validation asp.net-mvc asp.net-mvc-4

我有一个这样的模型:

[IsValidInput]
public class Input
{
    //different properties
}
Run Code Online (Sandbox Code Playgroud)

使用这样的自定义验证属性:

[AttributeUsageAttribute(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class IsValidInput : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        try
        {
            ExternalValidator.Validate(value);
        }
        catch (CustomException ex)
        {
            foreach(var errorText in ex.GetDescriptions())
            {
                this.ErrorMessage = this.ErrorMessage + errorText;
            }
            return false;
        }
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个包含多个错误的 ErrorMessage 对象。我想以某种方式返回多个 ErrorMessage 对象,这样在我看来,我将拥有一个包含多个列表项的列表,如下所示:

  • 验证错误1
  • 验证错误2

如何返回 ErrorMessages 列表来解决这个问题?

use*_*075 2

我找到了一个解决方法:

我将在错误消息中附加一些 html 标签,如下所示:

foreach(var errorText in ex.GetDescriptions())
{
    this.ErrorMessage = this.ErrorMessage + txt + @"</li><li>";
}
this.ErrorMessage = this.ErrorMessage.Remove(this.ErrorMessage.Length - 4);
Run Code Online (Sandbox Code Playgroud)

并在我的视图中添加@Html.Raw:

@if (Html.ValidationSummary() != null) { @Html.Raw(HttpUtility.HtmlDecode(Html.ValidationSummary().ToString())); } 
Run Code Online (Sandbox Code Playgroud)

这将为我提供带有我想要的验证结果的 html 列表。