ValidationResult中的memberNames未按预期工作

时间:2014-02-13 14:09:13

标签: asp.net-mvc-5

我正在通过在类级别附加到模型的模型验证器执行一些模型验证。如果我发现错误,我需要能够将该错误附加到视图中的相关字段,以便可以向用户清楚地显示该错误。

但是,只需将memberNames传递给ValidationResult就不会做任何事情。相反,我发现我需要在控制器中重新验证,然后填充ModelState对象。

以下是代码:

public class CompletedMilestoneInCorrectOrderAttribute : ValidationAttribute
{
    private const string DefaultErrorMessage = "Milestones cannot be completed out of sequence";

    public CompletedMilestoneInCorrectOrderAttribute()
        : base(DefaultErrorMessage)
    {
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var model = (RevisionEditViewModel)validationContext.ObjectInstance;

        var previousCompleted = true;
        var loop = 0;
        var members = new List<string>();

        foreach (var rm in model.RevisionMilestones)
        {
            if (rm.Completed && !previousCompleted)
            {
                members.Add("revisionMilestones[" + loop + "].ExpectedCompletionDate");
                members.Add("revisionMilestones[" + loop + "].Completed");
            }

            if (!rm.NotApplicable)
            {
                previousCompleted = rm.Completed;
            }

            loop++;
        }

        if (members.Any())
        {
            return new ValidationResult(DefaultErrorMessage, members);
        }

        return null;
    }
}

在控制器中

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(RevisionEditViewModel model)
    {
        //without this code the error never gets attached to the correct field in the view
        var validationContext = new ValidationContext(model, null, null);
        var validationResults = new List<ValidationResult>();
        Validator.TryValidateObject(model, validationContext, validationResults);
        foreach (var validationResult in validationResults)
        {
            foreach (var memberName in validationResult.MemberNames)
            {
                ModelState.AddModelError(memberName, validationResult.ErrorMessage);
            }
        }

        if (ModelState.IsValid)
        {
            *snip*
        }
        else
        {
            *snip*
        }
    }

任何人都知道发生了什么事吗?如何更正它,以便不再需要控制器中的混乱代码?

干杯迈克

0 个答案:

没有答案