I am trying to get JQuery events to work with partial views in ASP.NET MVC. However, after you load a partial view through Ajax, JQuery seems not able to fire events for any of the elements in the partial view. I suspect that this issue will also happen if you are using other frameworks or JavaScript libraries to load partial html code with Ajax.
For instance, consider the following example:
Controller:
public class TestController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult LoadPartialView()
{
return View("PartialView");
}
}
Index.aspx
<script type="text/javascript">
$(document).ready(function() {
$("#button").click(function() {
alert('button clicked');
});
});
</script>
<div>
<%using(Ajax.BeginForm("LoadPartialView", new AjaxOptions { UpdateTargetId="PartialView"})){ %>
Click <input type="submit" value="here" /> to load partial view.
<% } %>
</div>
<br /><br />
<% Html.RenderPartial("PartialView"); %>
PartialView.ascx
<div id="PartialView">
Click <input type="button" id="button" value="here"></input> to display a javascript message.
</div>
Once the page loads for the first time, you can click on the "Click here to display a Javascript message" and you will get a Javascript alert message that says "button clicked". However, once you click on the "Click here to load partial view", clicking on the button that is supposed to bring the Javascript alert message doesn't have any effect. It seems that the 'click' event is not being fired anymore.
Does anyone know why this issue occurs with JQuery and how to fix? This issue also occurs with other JQuery plugins that use events.