我有一個Address類,用於我的模型中的MailingAddress和BillingAddress屬性。我希望MailingAddress是必需的,但不是BillingAddress,但是我沒有看到用DataAnnotations執行此操作的方法。有條件地讓MVC類屬性/類
如果我能夠在MailingAddress屬性上設置[Required]屬性,並以某種方式定義Address類應該如何處理所需邏輯的邏輯,我覺得這將是一個簡單的解決方案。
任何想法?
我有一個Address類,用於我的模型中的MailingAddress和BillingAddress屬性。我希望MailingAddress是必需的,但不是BillingAddress,但是我沒有看到用DataAnnotations執行此操作的方法。有條件地讓MVC類屬性/類
如果我能夠在MailingAddress屬性上設置[Required]屬性,並以某種方式定義Address類應該如何處理所需邏輯的邏輯,我覺得這將是一個簡單的解決方案。
任何想法?
如果你的問題是如何在你自己的邏輯中使用Required屬性,那麼答案就是使用反射。原諒我,如果這不是你的問題。
從有問題的類型獲取所有屬性,然後查看它是否用RequiredAttribute裝飾。
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
}
}
編輯:固定在代碼一個錯字
編輯2:擴展代碼例如
這僅僅是一個奇夸克其彈出到我的頭:
一個簡單的解決方案可能是子地址到OptionalAddress。
我不認爲必需的屬性會繼承到子類。
[AttributeUsage (Inherited = False)]
如果需要也會想到。
更MVCish解決方案可能是實現自定義模型粘合劑(完全未經測試):
public override object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
var address = base.BindModel(controllerContext, bindingContext) as Address;
if (bindingContext.ModelName.EndsWith("BillingAddress"))
{
foreach (PropertyInfo p in address.GetType().GetProperties())
{
Attribute a = Attribute.GetCustomAttribute(p, typeof(RequiredAttribute));
if (a != null
&& propertyInfo.GetValue(address, null) == null
&& bindingContext.ModelState[bindingContext.ModelName
+ "." + p.Name].Errors.Count == 1)
{
bindingContext.ModelState[bindingContext.ModelName + "." + p.Name].Errors.Clear();
}
}
return address;
}
許多選項可在此之前問到的問題:
ASP.NET MVC Conditional validation
您是否需要此驗證是否在客戶端完成?
IValidateableObject將與您的任何現有屬性結合使用,並可提供額外的自定義驗證。
謝謝你的迴應,但我不認爲這就是我真正想要的。我需要能夠讓我的Address類成爲必需的,但只能用於父類中的MailingAddress屬性,而不用於BillingAddress屬性。 –
這不是所需的類,而是MailingAddress屬性。然後,您可以在父類中使用[Required]裝飾MailingAddress,而不是使用typeof(Address),如上所示使用typeof(<父類>) – havardhu