5

I'm probably making a stupid mistake somewhere. I would appreciate your help in the following.
I have sample MVC3 application with a single editable field that is displayed to user with TextBoxFor method. In the Index(POST) action I change the value but it still remains the same. What am I doing wrong?

My code:
Model:

public class TestModel
{
    public string Name { get; set; }
}

View:

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

Controller:

public ActionResult Index()
{
    return View("Index", new TestModel() { Name = "Before post" });
}

[HttpPost]
public ActionResult Index(TestModel model)
{
    model.Name = "After post";
    return View("Index", model);
}

If I replace TextBoxFor with TextBox or DisplayTextFor then it works correctly.

LINQ2Vodka
  • 2,996
  • 2
  • 27
  • 47
  • Are you defiantly sure that the `HttpPost` `Index` is being called? – rhughes Dec 10 '13 at 09:27
  • @rhughes yes. Firstly, it works well with TextBox instead of TextBoxFor. Second, i've just set breakpoints in both actions and in the view, pressed "submit" and saw HttpPost Index was fired, then a breakpoint inside view. – LINQ2Vodka Dec 10 '13 at 09:34

1 Answers1

14

I believe you must call ModelState.Clear() inside your [HttpPost] action, before you set the new value.

According to this answer, which has a very good explanation: How to update the textbox value @Html.TextBoxFor(m => m.MvcGridModel.Rows[j].Id)

See this too: ASP.NET MVC 3 Ajax.BeginForm and Html.TextBoxFor does not reflect changes done on the server Although it seems you're not using Ajax.BeginForm, the behavior is the same.

Including an example as suggested by @Scheien:

[HttpPost]
public ActionResult Index(TestModel model)
{
    ModelState.Clear(); 
    model.Name = "After post";
    return View("Index", model);
}
Community
  • 1
  • 1
BrenoSarkis
  • 305
  • 2
  • 13
  • 1
    Confirmed. Adding ModelState.Clear() before setting new value to model.Name does indeed allow update to the view. – scheien Dec 10 '13 at 09:38
  • Now I have change my understanding of how MVC works... Will accept the answer just after read it to end :) – LINQ2Vodka Dec 10 '13 at 09:40
  • I've made a couple applications without knowing it :) Thank you. – LINQ2Vodka Dec 10 '13 at 09:46
  • You're welcome @Jim, I had to research too! then I came across Darin's answer which made me remember that I've run through this before, but I couldn't give you an answer without the 'whys'. – BrenoSarkis Dec 10 '13 at 09:48