Roy_Dorsthorst Roy_Dorsthorst - 2 months ago 9
Ajax Question

Changing css in partial view using JQuery

I've got a view with a button and below that a div that is filled using ajax and a partial view.

This is the code that belongs to the button on the view;

$(document).on('click', '.btn-release', function () {
StartReleaseVersionEdit();
ReleaseVersionEdit();
}


Using Ajax I can alter the data that is displayed inside the table, this happens when I click the button at the top of the page;

function StartReleaseVersionEdit() {
var url = '@Url.Action("ChangelogMavisTabel")';
url = url + '?order=0&paging=1000';
$.ajax({
type: "GET",
cache: false,
url: url,
success: function (data) {
$("div#changelog").html(data);
}
});
}


This code works flawlessly. Once I want to alter the css of an element inside this partial view using JQuery to set the display to none, it works for a split second but then returns to its default value right after.

function ReleaseVersionEdit(){
$('.releasebutton').css('display','inline');
// .releasebutton default display=none
}


What can I do to make this work correctly? I can't put the JQuery inside the partial view's code because it is triggered by the button on the view.

CSL CSL
Answer

Move the ReleaseVersionEdit() function into the success method of your AJAX call, that way you can guarantee it is only called after the partial is loaded. Remember the AJAX call is asynchronous - jQuery.ajax():

$(document).on('click', '.btn-release', function () {
     StartReleaseVersionEdit();
  // ReleaseVersionEdit(); Remove from here as this could execute before the partial is loaded
}

function StartReleaseVersionEdit() {
    var url = '@Url.Action("ChangelogMavisTabel")';
    url = url + '?order=0&paging=1000';
    $.ajax({
        type: "GET",
        cache: false,
        url: url,
        success: function (data) {
            $("div#changelog").html(data);
            ReleaseVersionEdit(); // Added here so will always be called after the partial has been loaded
        }
    });
}