/** 简单整理了今天做的asp.net mvc+jQuery实现自动刷新的方法。
* 2011年8月31日20:04:46
*/
1、主页Js部分:使用setInterval定时执行
<script src="@Url.Content("~/jQuery/jquery-1.6.min.js")" type="text/javascript"></script>
<script type="text/javascript">
//最新消息每5秒刷新一次
setInterval(function () {
$.ajax({
url: '@Url.Action("HotNews", "Controller名称")', //异步请求Action
data: "id=@Model.id", //参数Id(可多个参数:data: "id=@Model.id&name=@Model.Name",)
type: "POST",
success: function (result) {
$("#partialContainer").html(result);
}
});
}, 5000);
</script>
<script type="text/javascript">
//最新消息每5秒刷新一次
setInterval(function () {
$.ajax({
url: '@Url.Action("HotNews", "Controller名称")', //异步请求Action
data: "id=@Model.id", //参数Id(可多个参数:data: "id=@Model.id&name=@Model.Name",)
type: "POST",
success: function (result) {
$("#partialContainer").html(result);
}
});
}, 5000);
</script>
页面中使用DIV接受返回的内容(.cshtml)
<div id="partialContainer">
</div>
</div>
2、异步请求的Action(.Controller)
[Description("最新消息(异步刷新调用)")]
public ActionResult HotNews(string id)
{
var contentList = new List<ContentListViewModel>();
var Contents = ContentService.GetHotNews(id, 3);//这里获取最新3条记录
if (Contents != null && Contents.Any())
{
contentList.AddRange(Contents.OrderByDescending(c => c.CreateTime)
.Select(h => new ContentListViewModel
{
Id = h.Id,
Name = h.Name,
Description = h.Description
});
}
return View(contentList);
}
public ActionResult HotNews(string id)
{
var contentList = new List<ContentListViewModel>();
var Contents = ContentService.GetHotNews(id, 3);//这里获取最新3条记录
if (Contents != null && Contents.Any())
{
contentList.AddRange(Contents.OrderByDescending(c => c.CreateTime)
.Select(h => new ContentListViewModel
{
Id = h.Id,
Name = h.Name,
Description = h.Description
});
}
return View(contentList);
}
3、Action对应对应页面(.cshtml)
@model List<Website.ViewModel.ContentListViewModel>
@{
ViewBag.Title = "";
Layout = null;
}
@if (Model != null && Model.Any())
{
foreach (var hot in Model)
{
<div class="hotNewsContent m10">
<h1>
@Html.ActionLink(hot.Name, "ContentDetail", "Controller名称", new { id = hot.ContentId }, null)
</h1>
<p>
@hot.Description
@Html.ActionLink("...详细", "ContentDetail", "Controller名称", new { id = hot.Id }, new { @class = "contentMore" })
</p>
</div>
}
}
else
{
<div class="hotNewsContent m10">
<h1>
<a href="#">暂无最新消息</a></h1>
<p>
</p>
</div>
}
@{
ViewBag.Title = "";
Layout = null;
}
@if (Model != null && Model.Any())
{
foreach (var hot in Model)
{
<div class="hotNewsContent m10">
<h1>
@Html.ActionLink(hot.Name, "ContentDetail", "Controller名称", new { id = hot.ContentId }, null)
</h1>
<p>
@hot.Description
@Html.ActionLink("...详细", "ContentDetail", "Controller名称", new { id = hot.Id }, new { @class = "contentMore" })
</p>
</div>
}
}
else
{
<div class="hotNewsContent m10">
<h1>
<a href="#">暂无最新消息</a></h1>
<p>
</p>
</div>
}