Model 为什么恢复字段的值?
我有两种查看方法(get和post)。在post方法中,我再次调用了get方法(因为数据无效),但当我再次看到查看页面时,我看到了预填充的数据。为什么?Model 为什么恢复字段的值?,model,asp.net-mvc-5,Model,Asp.net Mvc 5,我有两种查看方法(get和post)。在post方法中,我再次调用了get方法(因为数据无效),但当我再次看到查看页面时,我看到了预填充的数据。为什么? public ActionResult FillForm(string FormID) { FillRecordViewModel model = new FillRecordViewModel(); model.RefHost = ho
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
中视图的值的FillRecordViewModel
模型。如果不希望视图预先填充字段,请确保不传递模型,以便在[HttpGet]FillForm
中返回此返回视图()
我假设您使用的编辑器模板有@Html.EditorFor
,@Html.TextBoxFor
等
您看到的是MVC编辑器模板的预期行为,ModelState
中的值优先于视图模型中的实际值。这允许在post操作中提交表单后,显示相同的已发布数据以及任何验证错误。(前面有一些问题类似于或此)
如果不希望出现这种行为,可以在调用return FillForm(model.FormID)之前清除ModelState代码>关于您的post操作:
[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);
}
}
这样,将显示的表单将不包含提交的数据。
请注意,这也意味着post操作后显示的表单不会显示任何验证错误。(您只能使用类似于ModelState[“SomePropertyName”].Value=null;
的方法从ModelState中删除值,但如果您显示一个字段的验证错误,该字段现在为空或具有视图模型的默认值,则用户可能会感到奇怪)
希望这有帮助