我有两个视图方法(get和post)。在post方法中,我再次调用get方法(因为数据无效),但当我再次看到view页面时,我看到的是预填充的数据。为什么?
public ActionResult FillForm(string FormID)
{
FillRecordViewModel model = new FillRecordViewModel();
model.RefHost = host;
model.FormID = FormID;
model.Country = new SelectListModel();
model.Country.Values = (from i in db.Countries select new SelectListItem() { Text = i.CountryName, Value = i.CountryID.ToString() }).ToList();
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult FillForm(FillRecordViewModel model)
{
if (ModelState.IsValid)
{
}
else
{
return FillForm(model.FormID);
}
}
我想发生这种情况是因为您在[HttpGet] FillForm
中返回了带有View值的FillRecordViewModel
模型。如果您不希望视图预先填充字段,请确保您没有传递模型,以便在[HttpGet] FillForm
中返回此return View();
。
我假设您使用的是@Html.EditorFor
、@Html.TextBoxFor
等编辑器模板。
您看到的是MVC编辑器模板的预期行为,其中ModelState
中的值优先于视图模型中的实际值。这允许在发布操作中提交表单后,显示相同的已发布数据以及任何验证错误。(之前有一些问题,比如这篇或这篇博客文章)
如果您不希望出现这种行为,您可以在操作后调用return FillForm(model.FormID);
之前清除ModelState:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult FillForm(FillRecordViewModel model)
{
if (ModelState.IsValid)
{
}
else
{
//You can selectively clear the ModelState for specific properties, ignoring their submitted values
ModelState.Remove("SomePropertyName");
//Alternatively, you can clear the whole ModelState
ModelState.Clear();
return FillForm(model.FormID);
}
}
这样,将显示的表单将不包含提交的数据。请注意,这也意味着张贴操作后显示的表单将不会显示任何验证错误。(您只能使用ModelState["SomePropertyName"].Value = null;
之类的东西从ModelState中删除值,但如果您为现在为空的字段或视图模型的默认值显示验证错误,对用户来说可能会很奇怪)
希望这能有所帮助!