简体   繁体   中英

Jquery isnt loading Partial View like it should

I have problem loading partial views in mvc. Im trying to load the view with jquery and it kind of works. It either displays two divs filled with the right information or four filled with the same. But it loops through the array so the in paramater changes and I get a warning.

The process or thread has changed since last step

I have a array in jquery that is filled with four values and I need the value in that list as a paramater in the ActionResult.

The code I have

public ActionResult TvShow(string channel)
    {
        var model = un.SortAllPrograms(channel);
        return PartialView("TvShow", model);
    }

and jquery

$(document).ready(function () {
var nameOfChannel = ["TV3", "TV4", "TV6", "TV8"];
debugger
$.each(nameOfChannel, function (index, value) {
    $('.showContainer').append('<div class="number">' + value + '</div>');
    $('.number').load('Home/TvShow', { channel: value });
});

});

I would really appreciate some help or advice on how to make this work.

The issue is, For each ajax call, you are loading the response of the ajx call to the div with class number . So the ajax call which gets the last response will be used to update all the div's with that css class . This is the reason you are seeing more than one divs with same response at time, but this will be also random because every time your server takes different time to respond for each calls. Sometimes, the call for TV6 will be the one which takes more time. Since ajax is asynchronous, when the response comes back, it updates all the available divs with class number at that point . It is possible that your loop is executing it's second iteration at that, so you have only 2 divs present with that css class, hence it will update only those 2 divs.

Ideally you want to load to the div which was created for the specific in the array you are looping.

This should do it.

$(function() {

    var nameOfChannel = ["TV3", "TV4", "TV6", "TV8"];

    $.each(nameOfChannel, function (index, value) {
        var $d = $("<div class='number'>")
                                      .load('@Url.Action("TvShow")',{ channel: value });
        $('.showContainer').append($d);
    });


});

Keep in mind that, your current approach is making n number of calls to server (where n is the size of the array). You might consider sending the array as the parameter and making a single call which can return the markup for all the items, resulting in one single call. Use the approach which makes more sense to your use case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM