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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With