When I use the default model binding to bind the form parameters to a complex object, which is the parameter for the action, the structure remembers the values โโpassed to the first request, which means that any subsequent request to this action receives the same data as the first. Parameter values โโand validation status are stored between unrelated web requests.
Here is my controller code ( service represents access to the back of the application):
[AcceptVerbs(HttpVerbs.Get)] public ActionResult Create() { return View(RunTime.Default); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(RunTime newRunTime) { if (ModelState.IsValid) { service.CreateNewRun(newRunTime); TempData["Message"] = "New run created"; return RedirectToAction("index"); } return View(newRunTime); }
My.aspx view (strongly typed as ViewPage<RunTime >) contains directives like:
<%= Html.TextBox("newRunTime.Time", ViewData.Model.Time) %>
This uses the DefaultModelBinder class, which is designed to automatically save the properties of my model .
I hit the page, enter valid data (e.g. time = 1). The application correctly saves the new object with time = 1. Then I hit it again, enter different valid data (for example, time = 2). However, the data that is saved is original (for example, time = 1). This also affects the validation, so if my original data was invalid, all the data that I entered in the future are considered invalid. Restarting IIS or restoring my code resets the saved state.
I can fix the problem by writing my own hard-coded middleware, the basic naive example of which is shown below.
[AcceptVerbs(HttpVerbs.Post)] public ActionResult Create([ModelBinder(typeof (RunTimeBinder))] RunTime newRunTime) { if (ModelState.IsValid) { service.CreateNewRun(newRunTime); TempData["Message"] = "New run created"; return RedirectToAction("index"); } return View(newRunTime); } internal class RunTimeBinder : DefaultModelBinder { public override ModelBinderResult BindModel(ModelBindingContext bindingContext) {
Am I missing something? I do not think this is a browser session problem, since I can reproduce the problem if the first data is entered in one browser and the second in another.
asp.net-mvc inversion-of-control castle-windsor defaultmodelbinder
Alex scordellis
source share