Asp.Net MVC验证 – 依赖字段
发布时间:2020-05-24 14:29:29 所属栏目:asp.Net 来源:互联网
导读:我目前正在尝试通过MVC验证,并且遇到了一些需要字段的问题,具体取决于另一个字段的值.下面是一个例子(我还没想到) – 如果PaymentMethod ==“Check”,则需要ChequeName,否则可以通过. [Required(ErrorMessage = Payment Method must be selected)]public over
|
我目前正在尝试通过MVC验证,并且遇到了一些需要字段的问题,具体取决于另一个字段的值.下面是一个例子(我还没想到) – 如果PaymentMethod ==“Check”,则需要ChequeName,否则可以通过. [Required(ErrorMessage = "Payment Method must be selected")]
public override string PaymentMethod
{ get; set; }
[Required(ErrorMessage = "ChequeName is required")]
public override string ChequeName
{ get; set; }
我正在为[Required]使用System.ComponentModel.DataAnnotations,并且还扩展了ValidationAttribute以尝试使其工作,但我无法通过变量来进行验证(下面的扩展名) public class JEPaymentDetailRequired : ValidationAttribute
{
public string PaymentSelected { get; set; }
public string PaymentType { get; set; }
public override bool IsValid(object value)
{
if (PaymentSelected != PaymentType)
return true;
var stringDetail = (string) value;
if (stringDetail.Length == 0)
return false;
return true;
}
}
执行: [JEPaymentDetailRequired(PaymentSelected = PaymentMethod,PaymentType = "Cheque",ErrorMessage = "Cheque name must be completed when payment type of cheque")] 有没有人有这种验证的经验?将它写入控制器会更好吗? 谢谢你的帮助. 解决方法我会在模型中编写验证逻辑,而不是控制器.控制器应该只处理视图和模型之间的交互.由于它是需要验证的模型,我认为它被广泛认为是验证逻辑的地方.对于依赖于另一个属性或字段的值的验证,我(遗憾的是)没有看到如何完全避免在模型中为其编写一些代码,如Wrox ASP.NET MVC书中所示,有点像: 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,但那只能处理这种逻辑.甚至稍微复杂一点的东西需要另一个非常具体的属性,等等,它会很快变得疯狂. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
推荐文章
站长推荐
热点阅读
