ASP.NET MVC Form repopulation

Posted by ListenToRick on Stack Overflow See other posts from Stack Overflow or by ListenToRick
Published on 2009-01-04T18:52:12Z Indexed on 2010/04/10 9:33 UTC
Read the original article Hit count: 248

Filed under:
|
|
|

I have a controller with two actions:

[AcceptVerbs("GET")]
    public ActionResult Add()
    {
        PrepareViewDataForAddAction();
        return View();
    }


[AcceptVerbs("POST")]
    public ActionResult Add([GigBinderAttribute]Gig gig, FormCollection formCollection)
    {
        if (ViewData.ModelState.IsValid)
        {
            GigManager.Save(gig);
            return RedirectToAction("Index", gig.ID);
        }
        PrepareViewDataForAddAction();
        return View(gig);
    }

As you can see, when the form posts its data, the Add action uses a GigBinder (An implemenation of IModelBinder)

In this binder I have:

 if (int.TryParse(bindingContext.HttpContext.Request.Form["StartDate.Hour"], out hour))
        {
           gig.StartDate.Hour = hour;
        }
        else
        {
            bindingContext.ModelState.AddModelError("Doors", "You need to tell us when the doors open");
        }

The form contains a text box with id "StartDate.Hour".

As you can see above, the GigBinder tests to see that the user has typed in an integer into the textbox with id "StartDate.Hour". If not, a model error is added to the modelstate using AddModelError.

Since the gigs property gigs.StartDate.Hour is strongly typed, I cannot set its value to, for example, "TEST" if the user has typed this into the forms textbox.

Hence, I cant set the value of gigs.StartDate.Hour since the user has entered a string rather than an integer.

Since the Add Action returns the view and passes the model (return View(gig);) if the modelstate is invalid, when the form is re-displayed with validation mssages, the value "TEST" is not displayed in the textbox. Instead, it will be the default value of gig.StartDate.Hour.

How do I get round this problem? I really stuck!

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about mvc