简体   繁体   中英

ASP.Net Core MVC Disable validation when a specific button is pressed

I have 2 buttons on my form, a Submit and Save button. I want to be able to skip all validation when a user clicks the Save button. I've tried adding class="cancel" , formnovalidate , formnovalidate="formnovalidate" , disableValidation="true" to the Save button but none of them worked. Any help would be wonderful! I'm using 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" />

Firstly,you need to know,if you use _ValidationScriptsPartial ,it would generate the html like below:

Generate cshtml from:

<input asp-for="MyDate" class="form-control" />

to:

<input class="form-control" type="date" data-val="true"
    data-val-required="The MyDate field is required."
    id="MyDate" name="MyDate" value="">

formnovalidate and class="cancel" attribute could skip the validation in client side,but could not skip validation in server side.

To fix such issue,you could clear model state:

1.Model:

public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
}

2.View(add formnovalidate to 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.Action:

[HttpPost]
public IActionResult Request(Test test)
{
    if (!ModelState.IsValid)
    {
         ModelState.Clear();
         return View("Index");
    }
    return View("Index");
}

4.Result: 在此处输入图片说明

<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" />
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM