views:

603

answers:

3

I'm just trying to do some simple validation in MVC RC and am getting an error. For the purposes of this question, I am not using the UpdateModel.

Here is the code in the form:

<%= Html.TextBox("UserId")%>
<%= Html.ValidationMessage("UserId") %>

If I add the following line in the controller, I will get a NullReferenceException on the TextBox:

ModelState.AddModelError("UserId", "*");

So to fix this, I've also added the following line:

ModelState.SetModelValue("UserId", ValueProvider["UserId"]);

Why am I having to rebind the value? I only have to do this if I add the error, but it seems like I shouldn't have to do this. I feel like Im doing something incorrectly or just not familiar enough with binding.

It looks like Im not the only one who has seen this. Per request, here is the controller code:

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(FormCollection collection)
    {
        AppUser newUser = new AppUser();

        try
        {
            newUser.UserId = collection["UserId"];

            AppUserDAL.AddUser(newUser);

            return RedirectToAction("Index");
        }
        catch (Exception ex)
        {
            ViewData["ReturnMessage"] = ex.Message;

            ModelState.AddModelError("UserId", "*");
            ModelState.SetModelValue("UserId", ValueProvider["UserId"]);


            return View(newUser);
        }
A: 

Here you can read a description of this problem and how to solve it in another way.

zihotki
A: 

You definitely don't need to call SetModelValue.

Perhaps you just need your view to pull the Textbox from the model you passed in?

<%= Html.TextBox("UserId", Model.UserId)%>

That's how I do it.

Scott Hanselman
I tried this and it doesnt appear to work either. What's strange is that when I mouse over the line of code in the View that breaks, the Model object is not null and I can see all of the values.
Eric Brown
+4  A: 

Call this extension method:

        public static void AddModelError (this ModelStateDictionary modelState, string key, string errorMessage, string attemptedValue) {
        modelState.AddModelError (key, errorMessage);
        modelState.SetModelValue (key, new ValueProviderResult (attemptedValue, attemptedValue, null));
    }

From: Issues with AddModelError() / SetModelValue with MVC RC1

George Tsiokos
Ok, it looks like this is a problem with RC1. This will work, although it seems a little heavy handed. Thanks for the response.
Eric Brown
we'll see if this is fixed in the 1.0 release
Eric Brown