加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 条件数据注释

发布时间:2020-12-15 18:37:46 所属栏目:asp.Net 来源:网络整理
导读:有没有办法使数据注释有条件?我有一个桌子派对,我存储组织和人员。如果我添加一个组织,我不想要现场姓氏,但只有当我添加一个人。 public class Party{ [Required(ErrorMessage = "{0} is missing")] [DisplayName("Your surname")] public object surnam
有没有办法使数据注释有条件?我有一个桌子派对,我存储组织和人员。如果我添加一个组织,我不想要现场姓氏,但只有当我添加一个人。
public class Party
{
    [Required(ErrorMessage = "{0} is missing")]
    [DisplayName("Your surname")]
    public object surname { get; set; }

    [DisplayName("Type")]
    public object party_type { get; set; }
    ...
}

我想要一个需要的姓氏数据注释的条件,像:
if(party_type ==’P’)则需要姓氏,否则姓氏可以为空。

编辑
如果我必须把这个验证转移到控制器,那我该怎么做呢?如何从那里触发相同的错误信息?

解决方法

您可以使您的模型继承自 IValidatableObject,然后将自定义逻辑放入验证方法中。您还必须从属性中删除RequredAttribute。您将必须编写一些自定义JavaScript来验证客户端上的此规则,因为Validate方法不会转换为不显眼的验证框架。注意我改变了你的属性到字符串,以避免投射。

此外,如果您从属性中获得其他验证错误,那么它们将首先触发,并阻止验证方法运行,以便只有在基于属性的验证确定时才会检测到这些错误。

public class Party : IValidatableObject
{
    [DisplayName("Your surname")]
    public string surname { get; set; }

    [DisplayName("Type")]
    public string party_type { get; set; }
    ...

    public IEnumerable<ValidationResult> Validate( ValidationContext context )
    {
         if (party_type == "P" && string.IsNullOrWhitespace(surname))
         {
              yield return new ValidationResult("Surname is required unless the party is for an organization" );
         }
    }
}

在客户端,您可以执行以下操作:

<script type="text/javascript">
 $(function() {
      var validator = $('form').validate();
      validator.rules('add',{
          'surname': {
              required: {
                 depends: function(element) {
                      return $('[name=party_type]').val() == 'P';
                 }
              },messages: {
                  required: 'Surname is required unless the party is for an organization.'
              }
           }
      });
 });
 </script>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读