asp.net-mvc – 类mvc上的多个自定义验证属性

我正在创造一个更好理解的榜样.

[CustomValidator("Property1","Property2", ErrorMessage= "Error1")]
[CustomValidator("Property3","Property4", ErrorMessage= "Error1")]
public class MyViewModel
{
    public string Property1 {get; set;}
    public string Property2 {get; set;}
    public string Property3 {get; set;}
    public string Property4 {get; set;}
}

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class CustomValidator : ValidationAttribute
{
    All the required stuff is written.
}

只有第二个验证器(或列表中的最后一个验证器)被触发并忽略第一个验证器.
我不确定这是否适合这种情况.
有什么建议?

最佳答案 如果您使用Linq to SQL,为什么不尝试这样的东西

添加规则违规类以处理规则违规

public class RuleViolation
{
    public string ErrorMessage { get; private set; }
    public string PropertyName { get; private set; }
    public RuleViolation(string errorMessage)
    {
        ErrorMessage = errorMessage;
    }
    public RuleViolation(string errorMessage, string propertyName)
    {
        ErrorMessage = errorMessage;
        PropertyName = propertyName;
    }
}

现在在您的数据类上

[Bind(Exclude="ID")]
public partial class Something
{
    public bool IsValid
    {
        get { return (GetRuleViolations().Count() == 0); }
    }

    public IEnumerable<RuleViolation> GetRuleViolations()
    {
        if (String.IsNullOrEmpty(Name.Trim()))
            yield return new RuleViolation("Name Required", "Name");
        if (String.IsNullOrEmpty(LocationID.ToString().Trim()))
            yield return new RuleViolation("Location Required", "LocationID");
        yield break;
    }

    partial void OnValidate(ChangeAction action)
    {
        if (!IsValid)
            throw new ApplicationException("Rule violations prevent saving");
    }

}

在控制器的更新方法中,使用updatemodel方法更改属性

Something something = somethingRepo.GetSomething(id);
try
{
    //update something
    UpdateModel(something);
    somethingRepo.Save();
    return RedirectToAction("Index");
}
catch
{
    ModelState.AddRuleViolations(something.GetRuleViolations());
    return View(something);
}

这样,您可以在数据类更改时向其添加规则,并将其反映在更新等中

点赞