我的表单上有2个按钮,一个“提交”和“保存”按钮。我希望能够在用户单击“保存”按钮时跳过所有验证。我尝试将class="cancel"
,formnovalidate
,formnovalidate="formnovalidate"
,disableValidation="true"
添加到“保存”按钮,但是它们都不起作用。任何帮助都将是美好的!我正在使用ASP.NET Core 3.1。
Form
<form asp-action="Request">
...
...
<input name="answer" type="submit" value="Submit" class="btn btn-primary" />
<input name="answer" type="submit" value="Save" class="btn btn-secondary" />
</form>
<partial name="_ValidationScriptsPartial" />
<form asp-action="Request">
...
...
<input name="answer" type="submit" value="Submit" class="btn btn-primary" />
<input name="answer" type="submit" value="Save" class="btn btn-secondary cancel" />
</form>
@section Scripts{
<partial name="_ValidationScriptsPartial" />
}
首先,您需要知道,如果使用_ValidationScriptsPartial
,它将生成如下所示的html:
从中生成cshtml:
<input asp-for="MyDate" class="form-control" />
至:
<input class="form-control" type="date" data-val="true"
data-val-required="The MyDate field is required."
id="MyDate" name="MyDate" value="">
[formnovalidate
和class="cancel"
属性可以跳过客户端的验证,但不能跳过服务器端的验证。
要解决此问题,您可以清除模型状态:
1.Model:
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
}
2.View(将formnovalidate
添加到save input
):
@model Test
<form asp-action="Request">
<div>
Name:<input asp-for="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div>
Id:<input asp-for="Id" />
<span asp-validation-for="Id" class="text-danger"></span>
</div>
<input name="answer" type="submit" value="Submit" class="btn btn-primary" />
<input name="answer" type="submit" value="Save" formnovalidate class="btn btn-secondary" />
</form>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
3。动作:
[HttpPost]
public IActionResult Request(Test test)
{
if (!ModelState.IsValid)
{
ModelState.Clear();
return View("Index");
}
return View("Index");
}