简体   繁体   中英

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.

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);
    }

There isn't a way to do it with the built-in helpers. You have to do it manually

Using helpers to get the name:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM