Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3: How to force Html.TextBoxFor to use the model value rather than the POSTed value

In a number of situations I have had an issue where I have a model that is created on the server as a result of values posted back. Upon processing the model, some of the model values are changed and then redisplayed on the page. Is there some easy way to override the behavior that causes the MVC framework to use the POSTed value instead of my model value.

Example:

Model

public class MyModel {
    public string Value1 { get; set; }
}

Controller

public MyController : Controller {
    public ActionResult MyAction() {
        var model = new MyModel();
        model.Value1 = "OldValue";
        return View(model);
    }
    [HttpPost]
    public ActionResult MyAction(MyModel model) {
        model.Value1 = "NewValue";
        return View(model);
    }
}

View

@using(Html.BeginForm("MyAction", "My", FormMethod.Post) {
    @Html.TextBoxFor(m => m.Value1)
    <input type="submit"/>
}

When this page is first loaded, the textbox will contain "OldValue". After clicking submit, the text box still contains "OldValue" since that is what was POSTed back to the server, but I want it to create the second page (after the POST) with the value from the model (NewValue).

Is there an easy way to tell MVC to behave this way? I am not really sure what I am supposed to do in this situation to get my desired result.

Note - this is all pseudocode so I might have some errors, but the concept should be there.

like image 941
Leslie Hanks Avatar asked Aug 31 '12 19:08

Leslie Hanks


1 Answers

In your post redirect (Post - Redirect - Get pattern).

[HttpPost]
public ActionResult MyAction(MyModel model) {
    model.Value1 = "NewValue";
    return RedirectToAction("MyAction");
}

EDIT

Clear the model state to pass back an edited model

    [HttpPost]
    public ActionResult MyAction(MyModel model)
    {
        var newModel = new MyModel();
        newModel = model;
        ModelState.Clear();
        newModel.Value1 = "NewValue";
        return View(newModel);
    }
like image 94
Travis J Avatar answered Sep 28 '22 09:09

Travis J