0

好了,所以我有一個模型,看起來像:ASP.NET MVC 4不顯眼的確認上破複雜的模型

public class CustomerViewModel { 
    public string Password { get; set; } 
} 

public class CustomerAddViewModel { 
    public CustomerViewModel Customer { get; set; } 
    [System.ComponentModel.DataAnnotations.Compare("Customer.Password", ErrorMessage = "The confirm password should match")] 
    public string ConfirmPassword { get; set; } 
} 

我收到錯誤消息「無法找到名爲Customer.Password屬性」驗證。

我發現this SO Question,但它並沒有在validation.unobtrusive的最新版本,因爲申請,代碼如下所示:

element = $(options.form).find(":input[name='" + escapeAttributeValue(fullOtherName) + "']")[0]; 

其中escapeAttributeValue處理所有有效的特殊字符。

我試過使用System.Web.Mvc.Compare來代替,但是在渲染視圖時會導致錯誤。

任何想法?

+1

由於沒有Customer.Password屬性,您將收到錯誤消息。有一個密碼屬性,但它坐在不同的類 –

回答

1

出於屬性「Customer.Password」不存在的簡單原因。您可以定義視圖模型是這樣的:

public class CustomerAddViewModel { 
    public CustomerViewModel Customer { get; set; } 
    public string Password 
    { 
    get 
    { 
     return this.Customer.Password; 
    } 
    } 
    [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The confirm password should match")] 
    public string ConfirmPassword { get; set; } 
} 
+0

這真的很簡單嗎?我想象驗證是「聰明的」,足以遍歷對象層次結構。 – Manuel

+0

不,CompareAttribute只在當前的Model類中查找具有給定名稱的屬性。 – ataravati

+0

謝謝......當時我真的在毆打自己,認爲我在某處發生了一些小錯字,當時的確只是我的想法有誤。感謝您的簡單修復! – Manuel

0

正確的「MVC」做你正在做的是避免孩子在你的視圖模型對象的方式。視圖模型用於提供特定操作所需的最少信息。您註冊/創建客戶所需的所有信息都應該位於您的View Model中,並且當您使用有效信息提交表單時,接收該表單的行爲(或根據您的結構在數據層中的某個位置)將創建一個Customer基於該視圖模型的對象。

當然,你可能仍然可以繞過我剛剛說的話,但是你拒絕寫出這些額外的線條的時間越長,越難挖掘出你正在挖的洞。

+0

這個我完全理解。如果它完全在我的控制之下,那就是我要走的路線,但不幸的是,他們決定不想創建額外的視圖特定模型。有利的一面是,該應用程序將在稍後重新編寫,我將盡快完成! – Manuel