且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Asp.Net MVC验证 - 相关领域

更新时间:2023-02-25 13:29:39

我会写的验证逻辑模型,而不是控制。控制器应该只处理视图和模型之间的互动。因为它是一个需要验证的模式,我认为这是广泛认为是验证逻辑的地方。

I would write the validation logic in the model, not the controller. The controller should only handle interaction between the view and the model. Since it's the model that requires validation, I think it's widely regarded as the place for validation logic.

对于那些依赖于另一个属性或字段的值验证,我(不幸)没有看到如何完全避免写一些code为模型,比如在Wrox的ASP.NET MVC所示书,有点像:

For validation that depends on the value of another property or field, I (unfortunately) don't see how to completely avoid writing some code for that in the model, such as shown in the Wrox ASP.NET MVC book, sort of like:

public bool IsValid
{
  get 
  {
    SetRuleViolations();
    return (RuleViolations.Count == 0); 
  }
}

public void SetRuleViolations()
{
  if (this.PaymentMethod == "Cheque" && String.IsNullOrEmpty(this.ChequeName))
  {
    RuleViolations.Add("Cheque name is required", "ChequeName");
  }
}

声明做所有的验证将是巨大的。我敢肯定,你可以做一个 RequiredDependentAttribute ,但这只会处理这一类型的逻辑。的东西,甚至是稍微复杂,需要另一个pretty特定属性等,它们很快变得疯狂。

Doing all validation declaratively would be great. I'm sure you could make a RequiredDependentAttribute, but that would only handle this one type of logic. Stuff that is even slightly more complex would require yet another pretty specific attribute, etc. which gets crazy quickly.