MVC3: how to get Html.TextBox to use the model value, not the POSTED value

In a number of situations, I had a problem when I have a model created on the server as a result of the returned values. When processing a model, some of the model values ​​are changed and then re-displayed on the page. Is there an easy way to override the behavior that causes the MVC structure 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"/>
}

The first time this page loads, the text box will contain "OldValue". After clicking the “Submit” button, the text field still contains “OldValue”, since this is what was sent to the server, but I want it to create a second page (after POST) with the value from the model (NewValue).

MVC ? , , .

. , , .

+5
2

- (Post - Redirect - ).

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

,

    [HttpPost]
    public ActionResult MyAction(MyModel model)
    {
        var newModel = new MyModel();
        newModel = model;
        ModelState.Clear();
        newModel.Value1 = "NewValue";
        return View(newModel);
    }
+8

.

:

<input type="text" name="@Html.NameFor(m => m.MyField)" value="@Model.MyField"/>
0

All Articles