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; } ... } 我想要一个需要的姓氏数据注释的条件,像: 编辑 解决方法
您可以使您的模型继承自
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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – MVC / Razor – 当有下列括号时,Intellisen
- 有什么好的参考或工具可用于将ASP转换为ASP.NET?
- asp.net-mvc – .net Razor替代PHP echo
- 如何在ASP.NET核心rc2中禁用浏览器缓存?
- ASP.NET工作进程仍然以31kb的大小返回数据
- asp.net-mvc-3 – 通过URL导致控制器的DateTime导致ASP .NE
- asp.net-mvc – 如何将自定义工具添加到kendo编辑器
- asp.net-mvc – 实体框架 – 无法创建x类型的常量值.在此上
- asp.net – Dotnetopenauth oAuth服务提供商的解释
- asp.net – 和debug =“false”有什么区别?
推荐文章
站长推荐
热点阅读