Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap modal shown and hidden events not firing when injected via MVC partial view

In ASP.NET MVC 5, I have a bootstrap modal with id #modal which gets loaded as part of a view, when certain conditions are met (conditions omitted for brevity). I have #modal's shown.bs.modal and hidden.bs.modal functions implemented in a js file: main.js

So far so good, everything works fine. However, in the scenario where the above-mentioned conditions are not met, the modal is injected in the view's HTML via an AJAX call, as part of a partial view. The modal is exactly the same as the one mentioned before (same #modal id, same everything). However, this time the shown.bs.modal and hidden.bs.modal functions in main.js are not firing. Why is that?

like image 782
globetrotter Avatar asked Dec 08 '25 04:12

globetrotter


1 Answers

Change your event handlers in main.js:

$('#modal').on('shown.bs.modal', function (e) { ... });
$('#modal').on('hidden.bs.modal', function (e) { ... });

To delegated event handlers:

$('body').on('shown.bs.modal', '#modal', function (e) { ... });
$('body').on('hidden.bs.modal', '#modal', function (e) { ... });

You can replace body with whichever parent container you have #modal enclosed in. For a detailed explanation refer to the link in @Stephen Muecke's comment.

like image 135
trashr0x Avatar answered Dec 10 '25 18:12

trashr0x



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!