在许多情况下,我遇到了一个问题,即我在服务器上创建了一个模型,作为返回值的结果.处理模型后,会更改某些模型值,然后在页面上重新显示.是否有一些简单的方法来覆盖导致MVC框架使用POSTed值而不是我的模型值的行为.
例:
模型
public class MyModel { public string Value1 { get; set; } }
调节器
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); } }
视图
@using(Html.BeginForm("MyAction","My",FormMethod.Post) { @Html.TextBoxFor(m => m.Value1) <input type="submit"/> }
首次加载此页面时,文本框将包含“OldValue”.单击提交后,文本框仍然包含“OldValue”,因为这是POST回服务器的内容,但我希望它使用模型中的值(NewValue)创建第二页(在POST之后).
解决方法
在您的帖子重定向(后 – 重定向 – 获取模式).
[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); }