Search code examples
asp.net-mvcasp.net-mvc-partialviewunobtrusive-javascript

MVC 3 unobtrusive javascript links in refreshed partial view results


I have noticed that if you add a unobtrusive link in a refreshable partial view such as

<a href="/" data-delete-chapter="@Model.Chapter.ChapterId" class="delete-chapter" >
    Delete
</a>

wired up in javascript file in order to do a (less ugly) Jquery popup delete confirmation):

$("[data-delete-chapter]").each(function () {
    $(this).click(  ...

then upon refresh of the partial view via ajax these javascript handlers dispappear so you end up having to refresh them each ajax call. You can do this with OnSuccess AjaxOption: or directly in html as data-ajax-success such as my page previous button:

<a data-ajax="true" data-ajax-loading="#chapterAjaxImage" data-ajax-method="GET"
data-ajax-mode="replace" data-ajax-update="#chapterContainer"
href="ScrollChapterPrev/@(Model.VideoId)?pageNumber=@(Model.PageNumber)"
data-ajax-success="afterChapterRefresh()" class="gallery-prev">
    <img src="@Url.Content("~/Content/Images/play/chapter-slider-prev.png")" alt="prev"     />
</a>

however I feel that having data-ajax-success="afterChapterRefresh()" in the multiple places that refreshes my chapter list is not a lot less unobtrusive than making my original delete link use javascript thereby avoid the need to reference a refresh JS function:

<a href="javascript:deleteChapter(10)" class="delete-chapter" >
    Delete
</a> 

is there a better way or am I as close as unobtrusive that I can get in this special case?


Solution

  • Loading the content via ajax means , you are injecting something to the DOM , after the events ( click or whatever) bounded. So the newly injected elements wont have that event binding.

    jQuery on would help. on will work on current elements and future elements

    Change this

    $("[data-delete-chapter]").each(function () {
         $(this).click(function(){
          //do something
         });
    });
    

    to this

    $(document).on("click","[data-delete-chapter]"(function(){
      //do something
    });