这一定是非常明显的事情,但对我来说它看起来很奇怪。我有简单的 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();
。
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/