【问题标题】:ASP.net MVC - Text Box value retains the value that was POSTedASP.net MVC - 文本框值保留已发布的值
【发布时间】:2011-11-01 06:45:59
【问题描述】:

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

代码如下:

@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。我记得读过一些关于为什么会发生这种情况但现在似乎找不到的东西。我知道这是一个糟糕的例子,但我只是想记住它为什么这样做,以及解决方法是什么(重定向除外)。有没有办法让它显示更新的模型值而不是发布的表单值?

【问题讨论】:

  • 错字? Html.BeingForm()

标签: c# asp.net-mvc


【解决方案1】:

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多