8

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
Alex
  • 9,250
  • 11
  • 70
  • 81

2 Answers2

23

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

Community
  • 1
  • 1
Alex
  • 9,250
  • 11
  • 70
  • 81
  • 8
    You don't have to be so nuclear, if you're just setting `myModel.Amount` you can just do `ModelState.Remove("Amount")` – bhamlin Mar 01 '12 at 20:01
5

Try putting in

ModelState.Clear();
jasonbryan
  • 115
  • 1
  • 11