定期刷新部分视图(ASP.Net MVC)

8

我需要定期刷新.Net的部分视图。它可以通过Ajax.ActionLink工作,是否有类似的定期刷新功能?我是否可以不使用jQuery来完成它?


请查看以下链接:http://stackoverflow.com/questions/3167116/asp-net-mvc-refresh-table-data-every-5-seconds - raym0nd
你可以将以下代码放在 HTML 的 <head> 标签中:<META HTTP-EQUIV="REFRESH" CONTENT="10"> - raym0nd
能否不使用 JavaScript 实现? - Mr. Zen
@raym0nd,那样做刷新整个内容而不是我的部分视图,对吗? - Mr. Zen
3个回答

12

你可以通过以下代码来实现:

function loadPartialView() {
   $.ajax({
    url: "@Url.Action("ActionName", "ControllerName")",
    type: 'GET', // <-- make a async request by GET
    dataType: 'html', // <-- to expect an html response
    success: function(result) {
                $('#YourDiv').html(result);
             }
   });
}

$(function() {

   loadPartialView(); // first time

   // re-call the function each 5 seconds
   window.setInterval("loadPartialView()", 5000);

});

记得你的Action应该返回一个PartialView。 希望这能帮到你!


这在Chrome和Firefox中对我有效,但在IE 9中无效(没有尝试其他IE版本),但目前来说,这已经足够好了。+1 - Yetti

2
也许这篇文章可以帮助你:点击这里。你使用的是哪个版本的MVC?你可以为一个帮助方法设置一个指定的时间间隔,这是我见过的不使用js的唯一方法。

你可能会在使用这种方法时遇到麻烦。但这是我见过的唯一一种不使用js执行此操作的方法,其他所有方法都与js有关。 - Precious Roy
1
实际上,它使用的是 JavaScript,但 JavaScript 只是嵌入其中。 - Tae-Sung Shin

0

试试这个。

 $(document).ready(function () {
            var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))";
            $("#PartialViewDivId").load(url);
        setInterval(function () {
            var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))";
            $("#PartialViewDivId").load(url);
        }, 30000); //Refreshes every 30 seconds

        $.ajaxSetup({ cache: false });  //Turn off caching
    });

它进行了初始调用以加载div,然后随后的调用是在30秒间隔内进行的。

在控制器部分,您可以更新对象并将对象传递给局部视图。

public class ControllerName: Controller
{
    public ActionResult ActionName()
    {
        .
        .   // code for update object
        .
        return PartialView("PartialViewName", updatedObject);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接