ASP.net MVC - 文本框值保留POST的值

时间:2011-08-22 15:52:40

标签: c# asp.net-mvc

我的MVC应用程序中有一个包含文本框的表单。当表单POST到页面时,我对模型值进行了修改并重新显示视图。文本框仍显示已发布的值。

以下是代码:

@using( Html.BeginForm() ) {
    @Html.TextBoxFor( m => m.Foo )
    <input type="submit" value="Save" />
}

public class TestController : Controller {
    public ActionResult Index() {
        return View();
    }

    [HttpPost]
    public ActionResult Index(MyModel model) {
        model.Foo += "bar";

        return View(model);
    }
}

无论形式是什么(假设我输入foo)我添加“bar”并尝试再次显示表单。但是当重新显示表单时,我看到的只有foo。我记得读过为什么会发生这种情况,但现在似乎无法找到它。我知道这是一个糟糕的例子,但我只是想记住它为什么这样做,以及解决方法是什么(除了重定向)。有没有办法让它显示更新的模型值,而不是显示的表格值是什么?

1 个答案:

答案 0 :(得分:2)

您可以清除模型状态,帮助程序应显示新值。

[HttpPost]
public ActionResult Index(MyModel model) {
    model.Foo += "bar";
    ModelState.Clear();
    return View(model);
}
相关问题