2009-05-20 45 views
2

我想通過與在asp.net/mvc上的教程相同的方式使用ModelState驗證表單。但是我沒有我自己的數據庫或他們的對象,並想要對Formcollection進行驗證。我不知道,ModelState中是如何工作的,所以也許我在黑暗中拍攝我,但這裏是代碼,即崩潰:使用ModelState驗證表單

和NullReferenceException異常,我得到的文本框:

System.NullReferenceException:你調用的對象是空的。 System.Web.Mvc.HtmlHelper.GetModelStateValue(String key,Type destinationType)在System.Web.Mvc.Html.InputExtensions.InputHelper(HtmlHelper htmlHelper,InputType inputType,String name,Object value,Boolean useViewData,Boolean isChecked,Boolean setId ,布爾isExplicitValue,IDictionary 2 htmlAttributes) at System.Web.Mvc.Html.InputExtensions.TextBox(HtmlHelper htmlHelper, String name, Object value, IDictionary 2 htmlAttributes)at System.Web.Mvc.Html.InputExtensions.TextBox(HtmlHelper htmlHelper,String name,Object value)at ASP.views_authorized_account_aspx .__ RenderContent1(HtmlTextWriter __w,Control parameterContainer)in c:\ Users \ Trimack \ Documents \ Visual Studio 2008 \ Projects \ GuestManager \ AccountManager \ Views \ Authorized \ Account.aspx:line 61 *

任何想法?還是我完全錯了?

Trimack

回答

3

所以,對於每一個錯誤,您添加具有ModelState.AddModelError(),並再次調用查看,MVC框架將試圖找到它找到每一個錯誤的AttemptedValue。因爲你沒有添加它們,所以MVC會拋出異常。

http://forums.asp.net/p/1396019/3006051.aspx

如果有錯誤,那麼你還必須設置模型值以及模態錯誤

 
ModelState.AddModelError("Some_Key","Show some error message"); 
ModelState.SetModelValue("Some_Key", ValueProvider["Some_Key"]); 
+0

也是在這裏討論... http://stackoverflow.com/questions/647266/asp-net-mvc-html-textbox-throws-object-reference-not-set-to-an-instance-of-an – David 2009-05-20 14:08:06