4

I have a form in my MVC application that has a textbox. When the form is POSTed to the page, I make a modification to the model value and redisplay the view. The textbox still shows the value that was POSTed though.

Here is the code:

@using( Html.BeginForm() ) {
    @Html.TextBoxFor( m => m.Foo )
    <input type="submit" value="Save" />
}

public class TestController : Controller {
    public ActionResult Index() {
        return View();
    }

    [HttpPost]
    public ActionResult Index(MyModel model) {
        model.Foo += "bar";

        return View(model);
    }
}

Whatever is in the form (lets say I type in foo) I add "bar" and try to show the form again. But when the form is redisplayed all I see is foo. I remember reading something about why this is happening but can't seem to find it now. I know this is a poor example but I'm just trying to remember why it is doing this, and what the workaround is (other than redirecting). Is there a way to have it show the updated model value and not what the form value that was posted?

Dismissile
  • 32,564
  • 38
  • 174
  • 263

1 Answers1

2

You can clear the model state and the helper should display the new value.

[HttpPost]
public ActionResult Index(MyModel model) {
    model.Foo += "bar";
    ModelState.Clear();
    return View(model);
}
brheal
  • 1,237
  • 8
  • 14
  • Although it works it seems like it might not be the best approach (if there is one) since it might lead to some unintended results. [http://stackoverflow.com/questions/1775170/asp-net-mvc-modelstate-clear](http://stackoverflow.com/questions/1775170/asp-net-mvc-modelstate-clear) – brheal Aug 22 '11 at 17:06