且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

文本框恢复到原来的值,而ModelState中是有效的回传

更新时间:2023-11-28 09:15:16

我刚刚找到一个答案网上。

关键是回归模型前清除的ModelState

  [HttpPost]
公众的ActionResult指数(为MyModel基于myModel)
{
    // ModelState.Clear();
    计算机[国家] =无效;
    如果(ModelState.IsValid)
        计算机[国家] =有效;    VAR模型=新为MyModel {迈德特= myModel.MyData + 1};    ModelState.Clear();    返回查看(模型);
}

有关详细阅读这些文章2

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

Asp.net MVC ModelState.Clear

Maybe I'm missing something but when I have a form that posts back to the same action, the textbox value reverts to the old value. The following example should increment the value in the textbox on each POST. This does not happen, the value on the model is incremented and the model is valid.

IF however I clear the modelstate in the HttpPost Action (the comment in the code), everything works as expected.

Am I missing something?

Here's the code:

Model:

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

View:

<%@ 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>

Controller:

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);
    }

}

I just found an answer to this online.

The trick is to clear the ModelState before returning the 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);
}

For more detail read these 2 articles

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

Asp.net MVC ModelState.Clear