Search code examples
jqueryasp.net-mvc-5unobtrusive-validation

Using unobtrusive validation with two submit buttons, with no validation for one


I currently have a form using MVC 5 with two submit/post buttons--one to finalize the form (validate required fields among other validation), and one to just save the form (no real validation required). It works fine without including unobtrusive validation, but I'd like to use it...and when I do, the finalize button works okay, but the save button acts as though it's the finalize button--validating fields when it shouldn't be.

Is there a way to make this possible?

Code snippets are below.

View

{BeginForm code goes here}
@Html.LabelFor(model => model.TotalHours)
@Html.TextBoxFor(model => model.TotalHours)
@Html.ValidationMessageFor(model => model.TotalHours)
...
<input type="submit" value="Finalize" name="btnCreate" />
<input type="submit" value="Save and Quit" name="btnCreate" />

Model (using EF)

[Required(ErrorMessage = "Please enter the total number of hours.")]
[Display(Name = "Total Hours")]
public Nullable<decimal> TotalHours { get; set; }

Controller

[ValidateAntiForgeryToken]
[HttpPost]
[MultiBtn(Name = "btnCreate", Argument = "Finalize")]
public async Task<ActionResult> CreateFinalize(FormObj oForm)
{
    using (var dbContext = new DBContext())
    {
        if (ModelState.IsValid) { ... }
        else { return View(oForm); }
    }
}
[ValidateAntiForgeryToken]
[HttpPost]
[MultiBtn(Name = "btnCreate", Argument = "Save and Quit")]
public async Task<ActionResult> CreateFinalize(FormObj oForm)
{
    using (var dbContext = new DBContext())
    {
        // Remove model errors
        foreach (var modelStateVals in ModelState.Values)
            modelStateVals.Errors.Clear();
        // Process the form and save here
    }
}

Solution

  • I found that there's something in the html that you can add:

    <input class="cancel" />
    

    Unfortunately, the cancel class has been deprecated. But now it uses formnovalidate, which is what I needed.