Refreshing Partial View in MVC 3

末鹿安然 提交于 2019-12-08 06:35:43

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/8977043/refreshing-partial-view-in-mvc-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!