我在 MVC 中构建了一个简单的联系表单,它使用 Html 帮助程序类来生成文本框和下拉列表。我想清除文本框和下拉列表的值,就像使用 get 呈现页面时一样(仅在正确提交查询之后)。
我正在使用方法 ModelState.Clear()
来执行此清理,但我的表单值仍然存在,知道我在这里做错了什么吗?成功后,它会在代码中显示消息。您将在下面找到来 self 的 Controller 的代码副本。
感谢您抽出宝贵时间!
[HttpPost]
public ActionResult Contact(ContactUsViewModel model)
{
if (ModelState.IsValid)
{
bool isSuccess = _siteService.CreateInquiry(model.Inquiry);
if (isSuccess)
{
model.SuccessMessage = "Thank you for contacting us.";
ModelState.Clear();
}
}
model.InquiryTypes = InquiryTypes;
return View(model);
}
最佳答案
如果成功,只需在 Post-Redirect-Get 之后重定向到您的 GET 操作图案:
public ActionResult Contact()
{
var model = new ContactUsViewModel
{
SuccessMessage = TempData["SuccessMessage"] as string
};
return View(model);
}
[HttpPost]
public ActionResult Contact(ContactUsViewModel model)
{
if (ModelState.IsValid)
{
bool isSuccess = _siteService.CreateInquiry(model.Inquiry);
if (isSuccess)
{
TempData["SuccessMessage"] = "Thank you for contacting us.";
return RedirectToAction("Contact");
}
}
// since you are modifying the value of the InquiryTypes property
// you need to remove it from the modelstate to avoid getting the
// old value rendered by the helpers
ModelState.Remove("InquiryTypes");
model.InquiryTypes = InquiryTypes;
return View(model);
}
或者由于我不是 TempData 的忠实粉丝(因为它使用 Session 并且我个人总是在我的应用程序中禁用它),您可以简单地将查询字符串参数传递给 Contact GET 操作,例如 (success=1
) 并在此操作中准备成功消息。
关于c# - ModelState.Clear 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9312618/