filip
filip

Reputation: 1503

MVC4 - form doesn't show new model values

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>

}

Upvotes: 2

Views: 1003

Answers (1)

Felipe Miosso
Felipe Miosso

Reputation: 7339

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

Upvotes: 3

Related Questions