【问题标题】:How to prevent Fluent Validation from validating the model in certain condition如何防止 Fluent Validation 在特定条件下验证模型
【发布时间】:2020-09-16 02:06:00
【问题描述】:

我在表单上有两个名称不同的提交按钮。在控制器中 我有一个 HttpPost 操作方法,当单击两个提交按钮中的任何一个时,我都会调用它。下面是 action 方法的内部结构:

public ActionResult Save(Document model){
    if(Request["btnSave"]!=null){
       if (ModelState.IsValid){
         //go ahead and save the model to db
       }
    }else{//I don't need the model to be validated here
       //save the view values as template in cache
    }
}

因此,当单击名称为“btnSave”的按钮时,我需要先验证模型,然后再将其保存到数据库,但如果单击另一个按钮,我不需要任何验证,因为我只是将表单值保存在缓存以稍后将其回调。显然,在这种情况下我不需要验证任何东西。我使用流畅的验证。我的问题是无论我按哪个按钮都会收到警告。我可以控制 FV 何时验证模型吗?

【问题讨论】:

  • 是否需要在提交表单时阻止客户端验证或在操作执行后返回视图?
  • 在动作执行后返回的视图中?
  • 我不确定我是否理解您的目标:您想阻止在第二个按钮单击情况下执行任何服务器端验证规则?
  • 是的,点击第二个按钮时我不需要验证。

标签: asp.net-mvc fluentvalidation


【解决方案1】:

您可以将属性btnSave 添加到您的模型中:

public class Document
{
    public string btnSave {get; set;} // same name that button to correctly bind
}

并在您的验证器中使用条件验证:

public class DocumentValidator : AbstractValidator<Document>
{
    public DocumentValidator()
    {
        When(model => model.btnSave != null, () =>
        {
            RuleFor(...); // move all your document rules here
        });

        // no rules will be executed, if another submit clicked
    }
}

【讨论】:

  • 哈哈,这是个好主意。事实上我已经接近了,我只是不知道我可以写一个“独立”什么时候覆盖所有的验证逻辑。
  • 这里你根据UI上的逻辑来禁用它,最好是在action方法级别禁用,你知道怎么做吗?我正在寻找那个解决方案
猜你喜欢
  • 1970-01-01
  • 2011-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多