Refreshing Partial View in MVC 3

1.8k views Asked by At

I have a partial view that I have included on my _Layout.cshtml. It simply has a javascript function that changes an image based on the state of my system. I don't need to reload any data, I don't need to go to the code of the controller for anything, I simply need to reload that partial view.

I tried many of the examples that I found here but couldn't get any of them to work. I felt as if they were too complex for what I was doing anyway. Any guidance would be appreciated.

Thanks,

Steve

2

There are 2 answers

2
kprobst On

If the partial is loaded into the layout directly then there's no straightforward way to refresh it, because it's basically a part of the complete rendered page.

Your best bet is to render the partial using $.load or whatever equivalent you have available by hitting a controller method and rendering the result into a container (like a div). You would have to do this within a script that is loaded with the layout itself, by observing document.ready or something like that. Once you have that in place then it's trivial to keep reloading or refreshing the contents by hitting the controller method as many times as you need. For example in jQuery:

$(document).ready(function () {
    RefreshPartial();
    window.setInterval(RefreshPartial, 10000);
});

function RefreshPartial() {
    $('#container').load('/some/controller/endpoint', {parameters});    
}

This will call the controller method, and set the inner contents of the element identified with #container. You can call RefreshPartial as many times as you want.

1
Erik Funkenbusch On

Partial views only exist on the server. The only way to "refresh" the partial is to go back to the server to get it again.

Obviously, you must be doing something in the partial that needs refreshing. Whatever that is, should be callable from javascript to do the refresh.