Search code examples
asp.netasp.net-mvcrazor-2

ASP.NET MVC Post Returns Wrong Model Values


I have a simple post action that tries to return a new model back to the view from the post method. For some reason when I return new model I always see the model I have posted with why does that happen? I need to change the values of the model in the post action and return them back to the user but for some reason I am unable to do that?

public ActionResult Build()
{
    return View(new Person());
}

[HttpPost]
public ActionResult Build(Person model)
{
    return View(new Person() { FirstName = "THX", LastName = "1138" });
}

This is the view code;

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

    <fieldset>
        <legend>Person</legend>

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

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

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

If I open the form and type in "John" for first name and "Smith" for last name and post the form I get "John", "Smith" back from the post action and not "THX 1138" is there a way to override this behavior? I would also like to know why does it do that?


Solution

  • You can do this by instructing ASP.NET MVC to forget the posted values by adding this.ViewData = null; to your post action:

    [HttpPost]
    public ActionResult Build(Person model)
    {
        this.ViewData = null;
    
        return View(new Person() { FirstName = "THX", LastName = "1138" });
    }