2009-04-22 33 views
0

我創建了一個業務對象(具有屬性的普通舊類,沒什麼特別),它有一個空的構造函數,我將其用作我的View for/Member/Create(見代碼)中的一個強類型。對於在類中讀/寫的GUID和DateTime屬性,需要「值」

這一切工作正常,我從創建視圖中獲取對象「回發」 - 和我的方法memberToCreate.Save()實際上寫它應該是什麼,到數據庫。

但是完成之後,再次顯示創建視圖,並且guid和datetime-types字段引發驗證錯誤(「需要值」) - 除非它們是隻讀屬性。

我不想將屬性設置爲只讀,因爲它們需要從其他位置寫入。

如何解決這個問題?我可以根據需要/不需要「標記」房產嗎?

' 
' GET: /Member/Create 

Function Create() As ActionResult 
    Return View() 
End Function 

' 
' POST: /Member/Create 

<AcceptVerbs(HttpVerbs.Post)> _ 
Function Create(<Bind(Exclude:="MemberId")> ByVal memberToCreate As Biz.Member) As ActionResult 
    memberToCreate.Save() 
    Return View() 
End Function 

這讓我驗證錯誤:

Public Property DateOfBirth() As Date 
     Get 
      Return _DateOfBirth 
     End Get 
     Set(ByVal value As Date) 
      _DateOfBirth = value 
     End Set 
    End Property 

這不......

Public Readonly Property DateOfBirth() As Date 
     Get 
      Return _DateOfBirth 
     End Get 
    End Property 

回答

2

嘗試更改綁定屬性<Bind(Exclude:="MemberId, DateOfBirth")>

或者您可以使DateOfBirth屬性爲空,如果這可以爲​​您的業務邏輯。

+0

你的兩種方法都很好,並且教會了我一些東西。 我需要能夠將DateOfBirth設置爲值或無,基本上,所以在綁定中聲明式排除它不是一個可行的選項。 我也試過IsNullable,這是我之前沒有聽說過的。非常有趣的概念,但我真的不想將業務模型的屬性更改爲另一種類型,只是爲了解決驗證問題。 – Kjensen 2009-04-22 23:10:29

1

經過一些調查研究(與新的關鍵字cagdas提供給我),我來到了這個解決方案:

' 
' POST: /Member/Create 

<AcceptVerbs(HttpVerbs.Post)> _ 
Function Create(<Bind(Exclude:="MemberId,UserId,CreatedBy,ModifiedBy")> ByVal memberToCreate As eForening.Biz.Member) As ActionResult 

    If ModelState.Item("DateOfBirth").Value.AttemptedValue = String.Empty Then 
     ModelState.Item("DateOfBirth").Errors.Clear() 
    End If 

    If Not ModelState.IsValid Then 
     Return View() 
    End If 
    memberToCreate.Save() 
    Return RedirectToAction("Index") 
End Function 

這讓我處理空以及指定值出生日期 - 並讓我保持現有商務艙的方式(和我應該說的一樣)。

我基本檢查提供的DateOfBirth的值,如果提供的值是一個空字符串,我會重置該字段的錯誤計數並讓驗證繼續 - 在檢查Modelstate.IsValid之前。

也許有一個更優雅的解決方案,但它是迄今爲止我發現的最佳選擇。