Home > Enterprise >  Multiple Submit Button with Jquery submit
Multiple Submit Button with Jquery submit

Time:05-20

I have two buttons of type submit in a form

 <button type="submit" id="submitBtn" name="submitBtn" value="Save">Save</button>
 <button type="submit" name="submitBtn" value="Print">Print</button>

In the controller action, I have

 [HttpPost]
 public async Task<IActionResult> Report(Report model, string submitBtn)
 {
    switch(submitBtn)
    {
        case "Save": ...
                     break;
        case "Print": ..
                     break;
    }
 }

Above code works perfectly fine.

However, now I need to do some client side validation on the click on Save button. So in jquery I added

 $('#submitBtn').click(function (e) { // id of the Save button
        e.preventDefault();
        // do validation and if all good then submit
            $('#reportform').submit();
 });

Whats happening here is that when form is submitted, its hitting the controller action correctly however the value passed to the argument string variable submitBtn is null

 public async Task<IActionResult> Report(Report model, string submitBtn) <-- submitBtn is null

Any ideas why this happening? Please let me know if I missed anything.

CodePudding user response:

Before submitting the form you must append submitBtn to the form to send value to action.

$('#submitBtn').click(function (e) { // id of the Save button
        e.preventDefault();
        // do validation and if all good then submit

        $('#reportform').append("<input type='hidden' name='submitValue' value='Save' />");
        $('#reportform').submit();
});

and add Id for btnPrint

$('#printBtn').click(function (e) { // id of the Save button
    e.preventDefault();
    // do validation and if all good then submit

    $('#reportform').append("<input type='hidden' name='submitValue' value='Print' />");
    $('#reportform').submit();
});
 
  • Related