asp.net-mvc - 后期操作中的模型更改在 Html.TextBoxFor 中不可见?

标签 asp.net-mvc asp.net-mvc-4

这一定是非常明显的事情,但对我来说它看起来很奇怪。我有简单的 Controller 、具有一个属性的模型以及显示属性值并呈现该属性的编辑器的 View 。当我单击该按钮时,将发布表单并将感叹号附加到属性上。这个感叹号在我的 View 中可见,但仅在 p 标记中可见,而不是在 Html.TextBoxFor() 呈现的 input 标记中。

为什么 Html.TextBoxFor() 忽略我在后期操作中更新模型?

有什么方法可以改变 Html.TextBoxFor() 的这种行为吗?

查看

@model ModelChangeInPostActionNotVisible.Models.IndexModel

@using (Html.BeginForm())
{
    <p>@Model.MyProperty</p>
    @Html.TextBoxFor(m => m.MyProperty)
    <input type="submit" />
}

型号

namespace ModelChangeInPostActionNotVisible.Models
{
    public class IndexModel
    {
        public string MyProperty { get; set; }
    }
}

Controller

namespace ModelChangeInPostActionNotVisible.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new IndexModel { MyProperty = "hi" });
        }

        [HttpPost]
        public ActionResult Index(IndexModel model)
        {
            model.MyProperty += "!";
            return View(model);
        }
    }
}

点击提交按钮后的 HTML

<form action="/" method="post">    <p>hi!</p>
<input id="MyProperty" name="MyProperty" type="text" value="hi" />    <input type="submit" />
</form>

最佳答案

这是设计使然。

辅助方法使用 ModelState,因此如果您的请求的响应使用相同的模型,它将显示已发布的值。

这允许您在验证失败的情况下呈现相同的 View 。

为了确保显示新信息,请在返回之前添加:ModelState.Clear();

在此处了解更多信息:http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx

namespace ModelChangeInPostActionNotVisible.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new IndexModel { MyProperty = "hi" });
        }

        [HttpPost]
        public ActionResult Index(IndexModel model)
        {
            model.MyProperty += "!";
            ModelState.Clear();
            return View(model);
        }
    }
}

关于asp.net-mvc - 后期操作中的模型更改在 Html.TextBoxFor 中不可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13464407/

相关文章:

c# - Visual Studio 智能感知搞砸了

mysql - 将数据保存在 2 个表 mvc

c# - 我如何让两个按钮彼此相邻

c# - 设置全局化 Nuget 包

javascript - ASP.NET MVC View 中 javascript 文件的语法突出显示?

css - 使用 Release 部署网站时样式损坏

.net - Azure:HttpContext.Current.Session 对象是否由所有 WebRole 实例共享?

c# - 在同一应用程序项目上对 API 使用 Bearer Token 身份验证,对 MVC 使用 OpenId 身份验证

asp.net-mvc-4 - 在 mvc4 中使用多个同名的 html 助手

c# - MVC 中使用响应重定向