1

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?

3
  • where is the code that tells the submit button to call the Build action? Commented Jun 20, 2013 at 12:43
  • Can you show the generated HTML? Commented Jun 20, 2013 at 12:45
  • Have you put a breakpoint in "public ActionResult Build(Person model)" to make sure it's the action method that is being bound to? Commented Jun 20, 2013 at 12:51

1 Answer 1

5

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" });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.