开发者

SetTimeout to update a Partial View in MVC3 executes randomly

I'm working on an application that uses asp.NET mvc3. I created a partial view, and I call this partial view in a view, so that I can update a div without reloading the page. I use setTimeout (but I also tried setInterval) to define the refreshing time. The problem is that it does not work, it refreshes the div randomly, not following the time I set, and there is no logic that I can understand in it, sometimes it refreshes it twice, sometimes it waits, but never longer then the time I set. Th开发者_Python百科is is the code of the partial view. In the View I just call the partial view.

<script type="text/javascript">
var st;
function updateDiv() {
    st = null;
    clearTimeout(st);
    console.log("posting");
    $.post('@Url.Action("RefreshSelfUpdatingPartial")', function (data) {
        $('#SelfUpdatingPartialDiv').hide().slideDown("slow").html(data);
        //wait 15 seconds
        st = setTimeout(updateDiv, 15000);
    });
}
updateDiv();
</script>
<div id="SelfUpdatingPartialDiv">
test

</div>


"This is the code of the partial view. In the View I just call the partial view."

If all of the above code is in the partial view, doesn't that mean that the $.post() is going to then load all of the above into the <div>, resulting in a second copy of the above nested inside itself? As the timeouts run it'll just keep nesting more and more copies inside itself.

I'd suggest you move all of the above into your main view, then the partial view should return only whatever text you want to see in the <div> (and no JavaScript).

(If that's not what you meant by the statement I quoted then please update your post to explain more clearly where the above code sits and what the $.post('@Url.Action("RefreshSelfUpdatingPartial")) actually returns.)

(Plus, like Alex said, don't set your st variable to null before you pass it to clearTimeout() - though I think you can delete both lines because you don't need to clear a timeout after it's already triggered.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜