我有两种方法(获取和发布)用于查看。在post方法中,我再次调用get方法(因为数据无效),但是当我再次看到视图页面时,我看到预先填充的数据。为什么呢?
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);
}
}
答案 0 :(得分:0)
我认为这是因为您使用FillRecordViewModel
中的视图返回[HttpGet] FillForm
模型的值。如果您不希望视图预先填充字段,请确保您没有传递模型,因此在[HttpGet] FillForm
中您将返回此return View();
。
答案 1 :(得分:0)
我假设您使用的是@Html.EditorFor
,@Html.TextBoxFor
等编辑模板。
您看到的是MVC编辑器模板的预期行为,其中ModelState
中的值优先于视图模型中的实际值。这允许在后期操作中提交表单后显示相同的发布数据以及任何验证错误。 (以前有一些问题,例如this one或此blog post)
如果您不想要此行为,可以在发布帖子操作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中删除值,但如果您为现在为空的字段或视图模型的默认值显示验证错误,则可能会对用户造成奇怪的影响)
希望这有帮助!