Search code examples
javascriptasp.net-corerazorcontrolleronsubmit

Ask the user before submitting the form


I have a cshtml page with this code:

<form action='@Url.Action("ExportExcel", "Records")' method="post" target="_blank" onsubmit="return exportExcel(), true">
            <input type="hidden" name="filteredRecordsIds" id="filteredRecordsIds" value="" />
            <input id="btnExportExcel" type="submit" hidden="hidden" />
        </form>

in js the exportExcel function:

function exportExcel() {
 $('#filteredRecordsIds').val(filteredRecords.map(function (record) { return record.Id }));
    return true;
}

in controller Records:

public ActionResult ExportExcel(string filteredRecordsIds)
        {...}

I would like to add modal/popup, before the submitting that ask the user:

"Would you like to export with calculations?" with 2 buttons options: "Yes" or "No".

Depending on the user's response, I would like to send the answer to the controller (as second parameter).

How can I add that?

Thank You!


Solution

  • You can try to remove onsubmit,and use a button to open modal,then calling exportExcel when clicking Yes button:

    <form action='@Url.Action("ExportExcel", "Records")' method="post" target="_blank" id="myForm">
        <input type="hidden" name="filteredRecordsIds" id="filteredRecordsIds" value="" />
        <input id="btnExportExcel" type="button" value="submit" data-toggle="modal" data-target="#exampleModalLong"/>
    </form>
    
    <!-- Modal -->
    <div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    Would you like to export with calculations?
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" onclick="exportExcel()">Yes</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">No</button>
                </div>
            </div>
        </div>
    </div>
    

    js(submit the form in exportExcel):

    function exportExcel() {
                $('#filteredRecordsIds').val(filteredRecords.map(function (record) { return record.Id }));
                $("#myForm").submit();
            }