tags:

views:

757

answers:

1

Hello, I am trying to validate a form using ModelState generally the same way as in tutorials on asp.net/mvc. However I dont have my own database or their objects and want to validate against Formcollection. I am not sure, how ModelState works, so maybe I am shooting in the dark, but here is the code, that crashes:

<%=Html.TextBox(Html.Encode("atr_" + name.Key), ViewData["atr_" + name.Key])%> <%=Html.ValidationMessage("atr_" + name.Key, "*")%>

and NullReferenceException I get on the TextBox:

System.NullReferenceException: Object reference not set to an instance of an object. at System.Web.Mvc.HtmlHelper.GetModelStateValue(String key, Type destinationType) at System.Web.Mvc.Html.InputExtensions.InputHelper(HtmlHelper htmlHelper, InputType inputType, String name, Object value, Boolean useViewData, Boolean isChecked, Boolean setId, Boolean isExplicitValue, IDictionary2 htmlAttributes) at System.Web.Mvc.Html.InputExtensions.TextBox(HtmlHelper htmlHelper, String name, Object value, IDictionary2 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*

Any ideas? Or am I completely wrong?

Trimack

+2  A: 

So, for every error you add with ModelState.AddModelError() and call the View again, MVC Framework will try to find an AttemptedValue for every error it finds. Because you didn't add them, MVC will throw an exception.

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

If there are errors then you must also set the model value as well as the modal error

ModelState.AddModelError("Some_Key","Show some error message");
ModelState.SetModelValue("Some_Key", ValueProvider["Some_Key"]);
David Liddle
also discussed here... http://stackoverflow.com/questions/647266/asp-net-mvc-html-textbox-throws-object-reference-not-set-to-an-instance-of-an
David Liddle
You mean like this?if (formvals[1].Length < 5) ModelState.AddModelError(formvals.Keys[1], "Comments have to be at least 5 symbols long"); if (!ModelState.IsValid) return View();That is, what I have.
Trimack
Got it. Thanks.
Trimack