globetrotter
globetrotter

Reputation: 1047

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?

Upvotes: 3

Views: 1414

Answers (1)

trashr0x
trashr0x

Reputation: 6565

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.

Upvotes: 6

Related Questions