Home > front end >  ASP.NET Core disable validation when button is pressed
ASP.NET Core disable validation when button is pressed

Time:05-13

On the razor page, I have two buttons of type 'submit'.

The first button is used to add data to a local table, and the second button is used to add all columns in the database.

I want to prevent the first button from checking the validation of fields, only the second button checks the fields.

How to prevent the first button from checking the validation of the fields?

(ASP.NET Core)

CodePudding user response:

Add formnovalidate to the first button input. And formnovalidate attribute could skip the validation in client side,but could not skip validation in server side. So you could clear model state to skip validation in server side. Below is a mvc demo, you can refer to it.

Custom.cs:

public class Custom
    {
        public string name{ get; set; }
        public int Id { get; set; }        
    }

In HomeController.cs:

 public IActionResult Submit()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Submit(Custom custom)
        {
            if (!ModelState.IsValid)
            {
                ModelState.Clear();//clear model state to skip validation in server side
                return View("Submit");
            }
            return View("Submit");
        }

View:

@model nnnn.Models.Custom

@{
    ViewData["Title"] = "Submit";
}

<h1>Submit</h1>

<h4>Custom</h4>
<hr />
<div >
    <div >
        <form asp-action="Submit">
            <div asp-validation-summary="ModelOnly" ></div>
            <div >
                <label asp-for="name" ></label>
                <input asp-for="name"  />
                <span asp-validation-for="name" ></span>
            </div>
            <div >
                <label asp-for="Id" ></label>
                <input asp-for="Id"  />
                <span asp-validation-for="Id" ></span>
            </div>
            <div >
                <input type="submit" value="Create" formnovalidate  />
                <input  type="submit" value="Save"   />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Result:

enter image description here

CodePudding user response:

I am sure there are many ways to handle this...

You can direct to different controllers with different buttons and one of them would be like in this link and there are differents ways in it that you can use.. Check this out. I hope this helps.

Disable Validation Link

  • Related