2

I have a controller with 2 actions: 1 for displaying a form and 2nd for processing the submitted form. Smth like this:

public ActionResult Create()
{
    TestModel model = new TestModel() { Value1 = "aaa" };
    return View(model);
}

[HttpPost]
public ActionResult Create(TestModel model)
{
    model.Value2 = "bbb";
    return View(model);
}

As you can see I pre-populate Value1 with "aaa" so it appears on the form - this part works fine. However, when I submit the form I would like to fill other properties of the model object and re-display the form using the same view.

The problem is that on submit the form still displays the original model object and not the updated one i.e. only Value1 is populated with "aaa" and Value2 is empty.

The view I use is the Auto-generated one by scaffolding option:

@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
    <legend>TestModel</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Value1)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Value1)
        @Html.ValidationMessageFor(model => model.Value1)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Value2)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Value2)
        @Html.ValidationMessageFor(model => model.Value2)
    </div>

    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>

}

filip
  • 1,444
  • 1
  • 20
  • 40
  • as an fyi, you should be checking if `ModelState.IsValid`. Don't assume everything went well on your post action. – Brad Christie Nov 21 '13 at 12:29
  • this is just a sample code that I debug and can seen that the submitted object has all values populated – filip Nov 21 '13 at 12:32
  • possible duplicate of [@Html.Hidden has wrong value when populating a div with the response from an AJAX call](http://stackoverflow.com/questions/19953794/html-hidden-has-wrong-value-when-populating-a-div-with-the-response-from-an-aja) (just use `ModelState.Clear();`) – tpeczek Nov 21 '13 at 12:35

1 Answers1

3

You have to call ModelState.Clear() so the result will be the expected. MVC does assumptions when POSTed data is sent back to the client. But beware, clearing it manually might cause undesired results ...

You can read more about here: Asp.net MVC ModelState.Clear and http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx

Community
  • 1
  • 1
Felipe Miosso
  • 7,309
  • 6
  • 44
  • 55