好,我已經通過添加新的屬性的類中找到一個解決方法是:
public bool AddressIsRequired { get; set; }
建設我對於不同形式的模型,然後當,而不是使用正常所需的屬性我可以設置此,我在我自己自定義的驗證:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public sealed class AddressRequiredAttribute : RequiredAttribute, IClientValidatable
{
public AddressRequiredAttribute()
: base()
{
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
Type addresType = typeof(AddressModel);
if (context.ObjectType == addresType || context.ObjectType.BaseType == addresType)
{
AddressModel baseModel = (AddressModel)context.ObjectInstance;
if (baseModel != null && baseModel.AddressIsRequired)
{
return base.IsValid(value, context);
}
}
return ValidationResult.Success;
}
}
然後在我的AddressModel我能這樣記住我的屬性:
[AddressRequired(ErrorMessage = "Please enter your Postcode")]
public string Postcode { get; set; }
如果任何人能夠找到更好的方法來做到這一點(即只需更改數據註釋而不必創建單獨的屬性),我將打開此窗口。這種做法也意味着如果你擴展helper標籤並使用元數據來檢查IsRequired標誌,那麼用這個屬性標記的屬性將總是被標記爲必需的(我認爲這可能是因爲它繼承了必需的屬性)
是的......我一直在使用MVC,這是什麼問題?如何處理屬性? – Coops
我有大多數表單上不需要的地址模型,但是在我們發送小冊子時需要的地址模型中,我需要向基類添加一個'[Required(ErrorMessage =「請輸入您的郵編」)]''但只是爲了這一個形式 - 我不想爲此創建一個新的地址模型,因爲它使用它自己的partial來做一些ajax自動填充 – Pete
「...所以我需要添加一個[Required(ErrorMessage =「請輸入你的郵編」)]給基類,但只是爲了這一種形式......「基類是'無處不在'。你建議的方法不起作用嗎? – Coops