1

I am doing something fundamentally wrong. I have created a simple example of my problem.

I have a simple class as follows:

public class Example
{
    public string Text { get; set; }
}

I have created two methods on my controller

This is the view page you hit. It creates a new Example object.

public ActionResult Example()
{
    var model = new Example {
       Text = "test"
    };
    return View(model);
}

Then the post back when the form is submitted

[HttpPost, ValidateAntiForgeryToken]
public ActionResult Example(Example model)
{
    model.Text += "a";
    return View(model);
}

The view is as follows:

@model Stackoverflow.Example

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <h1>@Model.Text</h1>
    @Html.EditorFor(model => model.Text);
    <input type="submit" value="Save" />
}

When I first visit the page the heading and the text box have the same value

enter image description here

I press submit and the page loads again. The title has updated but the text box has the same value.

enter image description here

Why is the @Html.EditorFor(model => model.Text); not getting the updated value?

TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
Liam
  • 1,161
  • 12
  • 24

2 Answers2

1

You need to clear the model state on post method of controller

    [HttpPost, ValidateAntiForgeryToken]
    public ActionResult Example(Example model)
    {
        ModelState.Clear(); 
        model.Text += "a";
        return View(model);
    }
Arun Kumar
  • 885
  • 5
  • 11
1

When you post a model back to an ActionResult and return the same View, the values for the model objects are contained in the ModelState. The ModelState is what contains information about valid/invalid fields as well as the actual POSTed values. If you want to update a model value, you can do one of the following two things:

[HttpPost, ValidateAntiForgeryToken]
public ActionResult Example(Example model)
{
    ModelState.Clear(); 
    model.Text += "a";
    return View(model);
}

or

[HttpPost, ValidateAntiForgeryToken]
public ActionResult Example(Example model)
{
    var newValue = model.Text += "a";
    ModelState["Text"].Value = new ValueProviderResult(newValue,newValue, CultureInfo.CurrentCulture)
    return View(model);
}
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114