提交ActionResult的奇怪表单行为

时间:2016-12-02 16:31:09

标签: asp.net-mvc

似乎不应该这样,所以我不知道它为什么会这样。我喜欢这个结果,但担心我不能依赖它,因为我不知道它是如何工作的。

[HttpGet]  
public ActionResult Modify(System.Guid id)
{
  return View("Modify", LoadFromDatabase(id));
}


[HttpPost]
public ActionResult Modify(CaseModel myModel)
{
  //So odd behavior. If I redirect to the actual GET Modify, 
  //I loose any changes on the form. however if I perform the 
  //same actions but here in the Post... all my unsaved changes 
  //stick..why?

  //This one wipes any edits
  return RedirectToAction("Modify", new { id = myModel.ID});

  //This one actually leaves all my changes, even though 
  //I am re-creating the model from the database just like
  //the other ActionResult
  return View("Modify", LoadFromDatabase(myModel.ID));
}       

1 个答案:

答案 0 :(得分:0)

在上面的Stephen Muecke two中提及comments

  

你可以依赖它。 RedirectToAction()正在重定向到一个新页面,该页面基于CaseModel属性初始化ID的新实例(即从您的存储库中读取值。return View()返回当前的实例CaseModel如果您使用HtmlHelper方法生成表单控件,则会在您提交表单时使用ModelState添加的DefaultModelBinder值。 {3}}有关行为的更多解释)。 @Html.TextBoxFor(m => m.someProperty)将显示您发布的值,而@Model.someProperty将显示您在post方法中设置的“已更新”值

完美无缺。 HTML帮助程序使用ModelState(也称为ViewState)覆盖我的Model值。