JQuery events don't work with ASP.NET MVC Partial Views

Viewed 39618

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.

5 Answers

I have found a solution :

Juste try to make :

$(document).on("click", "YOUR_SELECTOR", function(e){
  /// Do some stuff ...
});

Instead of :

$("YOUR_SELECTOR").on("click", function(e){
  /// Do some stuff ...
});

The easiest way to handle this would be to utilize the live() method:

<script type="text/javascript"> 
         $(document).ready(function() { 
             $("#button").live('click', function() { 
                 alert('button clicked'); 
             }); 
         });    
</script>  

None of These solution worked for me, so i had to do these things to work:

  1. I created a partial view and put all my JavaScript references in that file
  2. I created a div like this
<div id="js">
       @Html.Partial("[Your_Path]")
</div>

3.When i load some partial page after that i do this in JavaScript:

$('#js').load('/Your_Controller/Your_Partial_function');
Related