Asp.net-Mvc-2

當 Modelstate 在回發時有效時,文本框恢復為舊值

  • January 7, 2015

也許我遺漏了一些東西,但是當我有一個回發到相同操作的表單時,文本框值會恢復為舊值。以下範例應在每個 POST 上增加文本框中的值。這不會發生,模型上的值會增加並且模型是有效的。

但是,如果我清除了 HttpPost 操作中的模型狀態(程式碼中的註釋),則一切都按預期工作。

我錯過了什麼嗎?

這是程式碼:

模型:

public class MyModel
{
   public int MyData { get; set; }
}

看法:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.MyModel>" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) {%>
   <%: Html.TextBoxFor(m => m.MyData)%>   (<%: Model.MyData%>)
                 <%: Html.ValidationMessageFor(m => m.MyData) %> <br />
   State :<%: ViewData["State"] %> <br />
   <input type="submit" />
<% } %>
</asp:Content>

控制器:

public class HomeController : Controller
{
   [HttpGet]
   public ActionResult Index()
   {
       return View(new MyModel { MyData = 0 });
   }

   [HttpPost]
   public ActionResult Index(MyModel myModel)
   {
       // ModelState.Clear();
       ViewData["State"] = "invalid";
       if (ModelState.IsValid)
           ViewData["State"] = "Valid";

       var model = new MyModel { MyData = myModel.MyData + 1 };
       return View(model);
   }

}

我剛剛在網上找到了這個答案。

訣竅是在返回模型之前清除模型狀態

[HttpPost]
public ActionResult Index(MyModel myModel)
{
   // ModelState.Clear();
   ViewData["State"] = "invalid";
   if (ModelState.IsValid)
       ViewData["State"] = "Valid";

   var model = new MyModel { MyData = myModel.MyData + 1 };

   ModelState.Clear();

   return View(model);
}

有關更多詳細資訊,請閱讀這 2 篇文章

http://forums.asp.net/p/1527149/3687407.aspx

Asp.net MVC ModelState.Clear

您應該使用Post-Redirect-Get 模式或不使用 Html Helpers。

參考:http: //blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx

基本上,MVC 期望文章中的任何重新顯示都是驗證錯誤,並重用發布的數據(視圖ModelState)進行重新顯示,而不是模型數據。指導是不要使用ModelState.Clear().

引用自:https://stackoverflow.com/questions/4615494