1

我有一个视图模型,因此在验证时,我想比较多个字段。我有一个自定义属性,它采用 viewmodel 并执行所需的验证。我正在使用自定义属性 [ValidateThisForm] 装饰视图模型类

[AttributeUsage(AttributeTargets.Class)]
public class ValidateThisForm : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        ViewModel _viewModel = value as ViewModel;

        if (_viewModel.TestOne == false && _viewModel.TestTwo == false)
        {
            ErrorMessage = "Form Incomplete: Please correct";
            return false;
        }
        else
        {
            return true;
        }
    }
}

问题是,我想执行几个“类级别”验证。因此,在我看来,我只能在表单的一个地方显示这些错误:

<td class = "field-validation-error">@Html.ValidationMessageFor(viewmodel => viewmodel)</td>

有没有办法让我在表单的不同位置显示多个“类级别”错误?

4

1 回答 1

0

Assuming your class currently looks something like this:

[ValidateThisForm]
public class MyViewModel
{
    public bool TestOne { get; set; }
    public bool TestTwo { get; set; }
}

If you have complex model-level validation you want to perform, where you can't simply annotate a single property, you can hook into the validation pipeline with IValidatableObject like this:

public class MyViewModel : IValidatableObject
{
    public bool TestOne { get; set; }
    public bool TestTwo { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    { 
      if (TestOne == false && TestTwo == false) 
      {
          yield return new ValidationResult("Form Incomplete: Please correct")
      }
    }
}

You can continue to yield return as many validation messages as you'd like. And you can display them all on the client with @Html.ValidationSummary

If you'd like the message to appear alongside a particular control, the ValidationResult constructor takes an overload with the memberNames of the affected properties so you could change the Validate method like this:

if (TestOne == false && TestTwo == false) 
{
    yield return new ValidationResult("Form Incomplete Message", new[] {"TestOne"})
}

Then you can provide the validation message for that particular property with the ValidationMessageFor HTML helper like this:

@Html.ValidationMessageFor(Function(model) model.TestOne )

For further reading, Scott Guthrie wrote about using IValidatableObject as part of his blog post introducing new features in MVC3 and had a follow up post with more detail on class level validation shortly thereafter.

于 2015-01-26T16:10:24.473 回答