2010-07-15 55 views
0

我意識到我只需將[Required]屬性添加到類屬性中,MVC就會自動以非常好的方式進行驗證。你可以在Asp MVC 2.0中添加動態驗證屬性嗎?

然而,我想要做的是在運行時分配屬性,這可能嗎?

例如,說我有

public class Cert {  
    public string MedicalNum { get; set; } 

    public int Certified { get; set; } 

... 
} 

我想使MedicalNum財產[必填](所以它在查看正確驗證)如果認證的屬性設置爲1。

這可能嗎?

回答

1

看看這個post on SO。基本上,通過示例propertiesMustMatch驗證來了解如何將數據註釋與多個屬性一起使用。這是什麼新的代碼可能是一個快速刺(注意,可能不是100%的上限語法正確,半成品)

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] 
public sealed class RequiredMedicalNum: ValidationAttribute 
{ 
    private const string _defaultErrorMessage = "{0} is required when certified is true"; 

    private readonly object _typeId = new object(); 

public RequiredMedicalNum(string medicalNum, string Certified) 
    : base(_defaultErrorMessage) 
{ 
    _medicalNum = medicalNum; 
    _certified= Certified; 
} 

public string _medicalNum 
{ 
    get; 
    private set; 
} 

public string _certified 
{ 
    get; 
    private set; 
} 

public override object TypeId 
{ 
    get 
    { 
     return _typeId; 
    } 
} 

public override string FormatErrorMessage(string name) 
{ 
    return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, 
     _medicalNum, _certified); 
} 

public override bool IsValid(object value) 
{ 
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); 
    object medicalNum = properties.Find(_medicalNum, true /* ignoreCase */).GetValue(value); 
    object certified= properties.Find(_certified, true /* ignoreCase */).GetValue(value); 
    if(certified == 1){ 
     Return String.IsNullOrEmpty(medicalNum); 
    } 
} 
} 
+0

感謝湯米,我會看一看的鏈接,我很欣賞你的代碼。今天下午會嘗試它,並從它的外觀,應該是我正在尋找的。 – 2010-07-15 18:42:16

相關問題