2009-05-20 47 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