0

I used ajax script and a partial view to post and retrieve a data without any postback or view flickering. Using the ajax script below would return the partialview with its content in a specified div element called "ajaxcom" as you can see on the script below. Now, I noticed that after the data("which is the partialview") is retrieve and displayed on the specified div element of a view, it seems that it's like a static or it became like read-only file because it doesn't respond anymore, in which I meant that, on that partialview I have some functionalities like button to click with corresponding jquery codes but it's not even firing or responding when you click any button on it. Is this normal scenario that if you want to display a partial view in a specified div element using ajax script would behave like this? If so, what are my options here if I still want to resume the functionalities within that partial view like I want to click a button on it? Any thoughts or suggestions? Thanks...

Ajax Script:

$.ajax({
    url: '/AjaxComms/AjaxComments',
    type: "POST",
    data: dataObject, 
    dataType: "json",
    success: function(result) {
        $.ajax({
            url: '/AjaxComms/DisplayPartial',
            type: "GET",
            contentType: 'application/html; charset=utf-8',
            data: dataObject, 
            dataType: "html",
            success: function (result) {
                $('#ajaxcom').html(result); // this is where I'm displaying my partial view
            }
        })
    },
    error: function (result) {
        alert(status);
    }
});

PartialView:

@model CRUD_AJAX.Models.CommentReplyModel

<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

<table id="mytable">  

  @foreach (var item in Model.Comments )
      {
    <tr >
        <td class="tdstyle" >

  <div style="font-weight:bold;">  @Html.DisplayFor(modelItem => item.name) </div> 

   <p class="comment more" style ="white-space: pre-line; margin-top:0px;margin-bottom:0px; border-radius: 4px 4px 4px 4px; max-width :500px; min-height :5px;  display :block; background-color: #CCCCFF">  @Html.DisplayFor(modelItem => item.comment) </p>
  <p style="margin-top:2px;margin-bottom:0px"> <input type="button" id="like" name="like" value="Like" style="color:blue;border:0px;background-color:inherit;cursor:pointer" /> <input type="button" class ="Reply" name="Reply" value="Replie(s)"  style="margin-bottom:0px;color:blue;border:0px;background-color:inherit;cursor:pointer" /></p>

   <div id="divReply" class ="divrep" style=" position:relative;left:50px; overflow:auto;margin-top:0px;margin-bottom:0px">
           <table>
           @foreach (var item2 in Model.Replies.Where(r => r.Id == item.Id))
              {
                 <tr >

                     <td >
                         <div style="font-weight:bold;"> @Html.DisplayFor(modelItem => item2.name) </div> 

                     <p class="comment more" style ="margin-top:0px;margin-bottom:0px;white-space:pre-line; border-radius: 4px 4px 4px 4px; max-width :445px; min-height :5px;  display :block; background-color: #CCCCFF;">@Html.DisplayFor(modelItem=>item2.reply)  </p>

                   </td>
                 </tr>
              } 
            </table>      

       <div class="editor-field" style="display:none; margin-bottom:5px;margin-top:5px">
        <input type="text" id="comidvalue" name="idrep" value="@Html.DisplayFor(modelItem => item.Id)" />
         <span class="field-validation-valid" data-valmsg-for="idrep" data-valmsg-replace="true"></span>
       </div>
      <br />
       <input type="text" id="namerep" name="namerep" style="width:445px;resize:none" />
       <span class="field-validation-valid" data-valmsg-for="namerep" data-valmsg-replace="true"></span>
      <br />
      <textarea id="reply" name="reply" style="width:445px;height:100px;resize:none" ></textarea>
      <span class="field-validation-valid" data-valmsg-for="reply" data-valmsg-replace="true"></span>
         <br />

       <input type="button" class="postrep" value="Post Reply" name="butname" style="cursor:pointer" /> 


            <br />
     </div>

        </td>       
    </tr>

    }

</table>
timmack
  • 590
  • 2
  • 12
  • 43
  • Could you paste your handler definitions? – Beri Oct 09 '14 at 07:04
  • You are overwriting the existing `html` of that `div`. All existing elements will be removed. – Aashray Oct 09 '14 at 07:05
  • You need to use event delegation for dynamically created elements –  Oct 09 '14 at 07:05
  • @Aashray So what is the best way to handle this type of scenario, So far this is what I can think of. I came from webforms and we can use ajax updatepanel to handle this. How to do this in mvc in the best possible ways? Any suggestions pls? – timmack Oct 09 '14 at 07:10
  • Look into this, this might be what you are looking for: http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Aashray Oct 09 '14 at 07:12
  • @StephenMuecke In which part should I apply that? In client-side? I can't figure it out, can you be more specific? – timmack Oct 09 '14 at 07:13
  • You need to update you question to include the partial view –  Oct 09 '14 at 07:18
  • 1
    OK, so if you want the click event for `` then you script should be `$('#ajaxcom').on('click, '.postrep', function() { alert('clicked'); });` –  Oct 09 '14 at 07:29
  • @StephenMuecke On this click event, which view should I attach this event handler? Is it on the parent view? or in the partial view which resides inside the div element of the parent view? – timmack Oct 09 '14 at 07:35
  • @StephenMuecke Thanks it works for me, I just need more understanding and exposure on client-side scripting that's why I was asking. You should post this as answer so I can give you a credit. – timmack Oct 09 '14 at 07:50
  • I'll post an answer with a bit more detail in an hour or so. –  Oct 09 '14 at 07:51

1 Answers1

1

When you attach a click handler to an element using

$('button.postrep').click(function() {...

it is applied to that element only. When your insert a new button element as you are doing with your AJAX call, the click event is not applied to the new element. In this case you need to use event delegation using jquery .on method. From the documentation "Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.".

In your case the closest element which is not dynamically updated is the element with id="ajaxcom" so your script to handle the click event of any dynamically added button with class="postrep" would be

$('#ajaxcom').on('click', '.postrep', function() { 
  // do something
});
  • Awesome, now I realized that client-side scripting is essential to web development in any form. I learn to love more on client-side scripting when I started to work on with MVC pattern although it's a bit tricky pattern but it's interesting. Now I have to focus on client-side scripting. Thanks for this info... – timmack Oct 09 '14 at 08:44