Search code examples
c#asp.net-corerazor-pagesbootstrap-5

Button submit not working when inside modal


I have a page that has the following code:

<div class="form-control">
        
        <input type="submit" value="Save" class="btn btn-primary"/>

        <!-- Button trigger modal -->
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
            Launch demo modal
        </button>
    </div>

and below the form:

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" >Save changes</button>
            </div>
        </div>
    </div>
</div>

the input type submit " <input type="submit" value="Save" class="btn btn-primary"/> " works, however when I click on the modal button, and the modal opens, the button inside "Save Changes" does not work.

I have also changed the button inside the modal to the same code as the Save button, but it also doesn't work. it doesn't call the OnPost button.

I have also tried adding a handler " asp-page-handler="Save" " and renaming the OnPostAsync to OnPostSaveAsync but does not work.

The inspect does not execute anything on the browser also.

I'm using razor pages asp net6 and the modal code comes from the bootstrap5 docs.


Solution

    • Your <div class="modal"> is likely located as a direct child of <body> instead of being inside its <form>...
    • ... but <button type="submit"> won't work unless the <button> itself is a descendant of the <form> element that should be submitted.
    • Fortunately, if the <button> is not a descendant of a <form>, then you can manually bind it using the <button form=""> attribute, which contains the id="" of the <form> you want to submit.