views:

335

answers:

4

i just about finished my first asp.net mvc site but i wasn't happy with the robustness of the validation.

i read up on validation and then added the below code to my Edit action in my UsersController:

  if (user_.firstname.Trim().Length == 0)
        {
            ModelState.AddModelError("firstname", "First Name is required.");
            return View();
        }

i just did a test on this and i now am getting errors in my view where the Model is null.

<% using (Html.BeginForm())
   {%>
<fieldset>
    <legend>Fields</legend>
    <p>
        <label for="Email">
            Login Name:
            <%= Model.loginName%>
        </label>
    </p>
    <p>

So in the above Model is null so i get an exception on Model.loginName. any idea whats going on here. If i remove the above code (the validation) everything works fine. (except that i can then put garbage in my database.

+3  A: 

See my response on a similar topic.

http://stackoverflow.com/questions/887757/validating-form-using-modelstate/888103#888103

Every time you add a model error to the ModelState and call the View again, the asp.net MVC framework tries to look for the attempted value. Also your View should return the user_ object to your strongly typed View.

if (user_.firstname.Trim().Length == 0)
{
    ModelState.AddModelError("firstname", "First Name is required.");
    ModelState.SetModelValue("firstname", ValueProvider["firstname"]);

    return View(user_);
}
David Liddle
There is a similar discussion here- http://forums.asp.net/p/1377232/2900140.aspx#2900140
RichardOD
A: 

In your controller you should add overloaded methods:

    public ViewResult UpdateUser()
    {
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult UpdateUser(user data)
    {
         if (user_.firstname.Trim().Length == 0)
         {
            ModelState.AddModelError("firstname", "First Name is required.");
            return View();
         }
         return View();
    }

With this solution your model in second method will not be null

Maxim
+1  A: 

You're getting a model null error because you're not passing a model to the view... is there anything stopping you from doing just that?

E.g.

if (user_.firstname.Trim().Length == 0)
{
    ModelState.AddModelError("firstname", "First Name is required.");
    return View(user_);
}

Although this should work as a work around... you should really have a good look at how your validation works. Validation should really be done elsewhere other than the controller, for instance, I put all my validation in the model itself.

Charlino
+1  A: 

I added the model in return method and now it started working.

Thanks for the answer.

return View(contactToEdit);

Sandeep