阅读后this very helpful answer我修改了一对方法,让它们都接受相同的 View 模型:
[ActionName("AddressCorrection"), HttpGet]
public IActionResult AddressCorrectionGet(AddressCorrectionViewModel model)
{
return View(model); // was return View();
}
[ActionName("AddressCorrection"), HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddressCorrectionPost(AddressCorrectionViewModel model)
{
if (ModelState.IsValid)
{
return View("Index", new ApplicationViewModel { SuccessMessage = "That worked." });
}
model.ErrorMessage = "Something went wrong";
return View(model);
}
问题是,在 AddressCorrectionGet
中调用 return View(model);
现在会将调用视为某种 POST
。具体来说,AddressCorrection.cshtml
上的验证器运行。我看到的不是一个可供输入的空白表单,而是一个带有一堆“必填字段缺失”消息的表单。
在这种情况下,如何防止 View 运行验证器?或者在更一般的情况下, View 如何知道它应该或不应该运行验证器(我认为这只是基于请求方法是 GET
还是 POST
。显然是错误的。),我如何明确地告诉 View 运行或不运行验证器?
最佳答案
在return View(model);
之前使用ModelState.Clear();
关于c# - 如何防止验证器在 HttpGet 上运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41321865/