我在表单上有两个不同名称的提交按钮。在控制器中我有一个 HttpPost 操作方法,当单击两个提交按钮中的任何一个时,我会调用该方法。下面是操作方法的内部结构:
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 何时应验证模型吗?
您可以向模型添加属性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
}
}