有条件地使MVC类属性/类成为必需 [英] Make MVC class property/class required conditionally

查看:75
本文介绍了有条件地使MVC类属性/类成为必需的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Address类,该类用于我的模型中的MailingAddress和BillingAddress属性.我希望MailingAddress是必需的,而不是BillingAddress,但是我没有看到使用DataAnnotations做到这一点的方法.

I have an Address class that is used for both a MailingAddress and BillingAddress property in my Model. I want the MailingAddress to be required, but not the BillingAddress, but am not seeing a way to do this with DataAnnotations.

如果我能够在MailingAddress属性上设置[Required]属性,并且以某种方式定义了Address类应该如何处理所需逻辑的逻辑,我觉得那将是一个简单的解决方案.

If I were able to set the [Required] attribute on the MailingAddress property and somehow define the logic for how the Address class is supposed to handle the required logic, I feel like that would be a simple solution.

有什么想法吗?

推荐答案

如果您的问题是如何在自己的逻辑中使用Required属性,则答案是使用反射.如果那不是你的问题,请原谅我.

If your question is how to use the Required attribute in your own logic, the answer is by use of reflection. Forgive me if that is not your question.

从有问题的类型中获取所有属性,然后查看其是否用RequiredAttribute装饰.

Get all properties from the type in question, then see if it is decorated with a RequiredAttribute or not.

class ParentClass
{
      [Required]
      public Address MailingAddress { get; set; }

      public Address BillingAddress { get; set; }
}

(...)

Type t = typeof(ParentClass);

foreach (PropertyInfo p in t.GetProperties())
{
    Attribute a = Attribute.GetCustomAttribute(p, typeof(RequiredAttribute));
    if (a != null)
    {
          // The property is required, apply your logic
    }
    else
    {
          // The property is not required, apply your logic
    }
}

修复了代码中的错字

扩展代码示例

这篇关于有条件地使MVC类属性/类成为必需的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆