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 publishes its data, the Add action uses GigBinder (IModelBinder implementation)
In this binder, I:
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 field with the identifier "StartDate.Hour".
As you can see above, GigBinder checks that the user types an integer into the text field with the identifier "StartDate.Hour". If not, the modelstate model is added using AddModelError.
Since the gigss.StartDate.Hour property is strongly typed, I cannot set its value, for example, "TEST", if the user entered this into the text field of the form.
Therefore, I cannot set the value of gigs.StartDate.Hour, since the user entered a string, not an integer.
Since the "Add Action" action returns a view and passes the model (return View (gig);), if the state of the model is invalid when the form is re-displayed using the mssages check, the "TEST" value is not displayed in the text box. Instead, it will be the value by default is gig.StartDate.Hour.
How do I get around this problem? I'm really stuck!
asp.net-mvc forms
iasksillyquestions
source share