在Html.TextBoxFor中看不到后期操作中的模型更改?

Pol*_*Pol 5 asp.net-mvc asp.net-mvc-4

这一定是非常明显的,但对我来说这看起来很奇怪.我有简单的控制器,带有一个属性的模型,以及显示属性值的视图,并为该属性呈现编辑器.单击按钮时,表单将被发布,并且感叹号将附加到属性.此感叹号在我的视图中可见,但仅在p标记中可见,而不是在input呈现的标记中Html.TextBoxFor().

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

有没有办法改变这种行为Html.TextBoxFor()

视图

@model ModelChangeInPostActionNotVisible.Models.IndexModel

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

模型

namespace ModelChangeInPostActionNotVisible.Models
{
    public class IndexModel
    {
        public string MyProperty { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

调节器

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

点击提交按钮后的HTML

<form action="/" method="post">    <p>hi!</p>
<input id="MyProperty" name="MyProperty" type="text" value="hi" />    <input type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)

Yan*_*net 10

这是设计的.

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

这是为了允许您在验证失败的情况下呈现相同的视图.

要确保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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


rar*_*rrr 6

Yan Brunet绝对正确,需要从ModelState中删除变量才能在控制器中进行修改.但是,您不必清除整个ModelState.您可以执行以下操作以仅删除要修改的变量:

 ModelState.Remove("MyProperty");
Run Code Online (Sandbox Code Playgroud)

如果您想保留用户输入的其他值,这将非常有用.