2010-12-03 77 views
3

我有一個視圖模型,看起來像這樣:如何使用DataAnnotations驗證ViewModel中只有部分字段?

public class Viewmodel 
{ 

    public int Type {get;set} // 0 if typeA, 1 if typeB 

    [Required] 
    public string AProperty1 {get;set} 

    [Required] 
    public string AProperty1 {get;set} 

    ... 

    [Required] 
    public string BProperty1 {get;set} 

    [Required] 
    public string BProperty1 {get;set} 
} 

有2種形式即得到這個視圖模型和形式上的用戶輸入AProperty1,AProperty2等,並BProperty,迴歸爲空。 與FormB相同。 窗體的類型(FormA或FormB)被分配給ViewModel.type字段。

所以問題是,在我的控制器中,我檢查了ModelState.IsValid屬性,它將在兩種方式都是錯誤的,因爲一半的字段總是空的。

一個可能的解決方案可能是以某種方式覆蓋ModelView中的ModelState.IsValid屬性,以便我可以將類型傳遞給它。但據我所知,沒有辦法。

還有其他解決方案嗎? (它最好能夠與客戶端驗證一起使用)

+0

IMO這裏的問題是,你有一個「視圖模型」,不與你的真實看法模型擬合。你應該分割它。 – onof 2010-12-03 09:07:16

+0

我知道這是一個錯誤的方式和問題的主要來源,但這是一個要求。 – GaGar1n 2010-12-03 09:12:25

回答

相關問題