Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET MVC Ajax Form keeps old input values - how to update to the model's value?

I have a properly working ajax form in my MVC3 application except for one caveat. After I submit the form and get the result, even though the passed in model has a different value for the input (Amount in the example below) the old value still shows up on the screen. I attribute this to the value being saved in the DOM and overriding/preventing the new value from the model. There are various ways to fix this by running a javascript function on one of the form events.

I would like to get feedback on what is the best way to handle this situation, preferably native to MVC and without javascript. Here are the code snippets:

Parent View:

<div id="MyContainder">
    @Html.Partial("MyPartialView", ClassContainingAmountProperty)
</div>

Partial View:

@using (Ajax.BeginForm(actionName: "myaction",
              ajaxOptions: new AjaxOptions() UpdateTargetId = "MyContainder"})
      @Html.EditorFor(x => x.Amount)
      <input type="submit" value="Save" />
)

Controller

myModel.Amount = SomeNewNumber;
return PartialView(myModel); //same partial view returned but with new amount
like image 348
Alex Avatar asked Mar 01 '12 19:03

Alex


1 Answers

As soon as I ask the question I found the answer! ASP.NET MVC 3 Ajax.BeginForm and Html.TextBoxFor does not reflect changes done on the server

You must call

ModelState.Clear();

inside the action before returning the partial view

like image 170
Alex Avatar answered Nov 09 '22 23:11

Alex