【问题标题】:How to Prevent Validators from Running on HttpGet?如何防止验证器在 HttpGet 上运行?
【发布时间】:2016-12-25 14:16:14
【问题描述】:

看完this very helpful answer我修改了一对方法,让它们都接受相同的视图模型:

[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 运行验证器?或者在更一般的情况下,视图如何知道它应该与不应该运行验证器(我认为这只是基于请求方法是 GET 还是 POST。显然是错误的。),以及如何我可以明确告诉视图运行还是不运行验证器?

【问题讨论】:

    标签: c# asp.net-mvc validation controller .net-core


    【解决方案1】:

    return View(model);之前使用ModelState.Clear();

    【讨论】:

    • 虽然我还不知道为什么这可行,但我知道这巧妙地解决了我的问题。谢谢你。我将阅读this and other related posts here 以更好地了解它是如何发挥作用的。
    猜你喜欢
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 2023-04-10
    • 2013-08-02
    相关资源
    最近更新 更多