Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextBoxFor is not refreshing after postback

Tags:

c#

asp.net-mvc

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.

like image 466
LINQ2Vodka Avatar asked Dec 12 '22 09:12

LINQ2Vodka


1 Answers

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);
}
like image 170
BrenoSarkis Avatar answered Dec 13 '22 21:12

BrenoSarkis