2010-02-24 24 views
2

我初始化我的字符串爲空白,而不是null。在MVC 1中運行良好,使用tryupdatemodel,因爲任何沒有文本的文本條目都會被設置爲空字符串,在MVC 2 RC2中顯然(至少從我的測試)它將它們設置爲null/nothing。所以現在我從我的驗證層獲取錯誤,要求那些空白不爲空。我發現的另一個問題是,現在通過反射調用了對象的每個屬性,包括我沒有在綁定包含語句中指定的屬性,甚至無法設置的只讀屬性。ASp.net MVC 2改變了tryupdatemodel的工作方式,修復我的代碼的最簡單方法是什麼?

任何人都有最簡單的方法來解決這些問題的想法,而不會完全改變我的所有代碼?或者我應該只是吮吸它和

+0

顯示偶然一些代碼? – Jimmy 2010-02-24 21:40:53

+0

它不會顯示太多。 暗淡數p作爲新的Person P.Name = 「」 tryupdatemodel(P) 如果名稱回發項目是空白的,p.name現在是空,不爲空。而在MVC 1下它將是空白的。 – Solmead 2010-02-24 23:31:48

回答

0

要解決這個字符串默認爲空,而不是「」我不得不這樣做第一:

Public Class NullToEmptyStringModelBinder 
Inherits DefaultModelBinder 

Protected Overrides Sub SetProperty(ByVal controllerContext As System.Web.Mvc.ControllerContext, ByVal bindingContext As System.Web.Mvc.ModelBindingContext, ByVal propertyDescriptor As System.ComponentModel.PropertyDescriptor, ByVal value As Object) 
    If value Is Nothing AndAlso propertyDescriptor.PropertyType Is GetType(String) Then 
     value = "" 
    End If 



    MyBase.SetProperty(controllerContext, bindingContext, propertyDescriptor, value) 
End Sub 
End Class 

,然後添加到應用程序啓動此:

ModelBinders.Binders.DefaultBinder = New NullToEmptyStringModelBinder 
0

關於你有沒有綁定屬性 - asp.net的MVC 2 RC具有從輸入驗證這種變化模型驗證,here is how it works now
我想你有串的問題也由於RC2所做的更改,請查看發行說明。

+0

是的,我想這可能是它調用所有屬性的原因,我認爲這與它們如何激發模型上的所有驗證屬性有關。 我正在查看它的發行說明中的​​字符串內容。 – Solmead 2010-02-24 23:29:32

相關問題