asp.net-mvc-2 - 当 Modelstate 在回发时有效时,文本框恢复为旧值

标签 asp.net-mvc-2 binding

也许我遗漏了一些东西,但是当我有一个回发相同操作的表单时,文本框值将恢复为旧值。以下示例应在每个 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>

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

}

最佳答案

我刚刚在网上找到了这个问题的答案。

诀窍是在返回模型之前清除 ModelState

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

有关更多详细信息,请阅读这两篇文章

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

Asp.net MVC ModelState.Clear

关于asp.net-mvc-2 - 当 Modelstate 在回发时有效时,文本框恢复为旧值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4615494/

相关文章:

python - VTK Marching 立方体实现的替代方案

wpf - 如何使用 Enum 属性中的 DataTrigger?

c# - ASP.NET MVC 2 显示()

c# - 开发 Multi-Tenancy asp.net MVC 应用程序时要记住什么?

c# - 模拟 MembershipUser

wpf - 如何传递整数作为 ConverterParameter?

wpf - 如何绑定(bind)到 XAML、WPF 中的附加属性

c# - 如何: Read the content of a selected DataGrid row

asp.net-mvc - Asp.Net MVC - 进修类(class)

asp.net - "Dynamic operations can only be performed in homogenous AppDomain"错误