在MVC 5中刷新部分视图Div

我正在尝试刷新MVC 5中的局部视图div,以便表格显示新的SQL数据。 但是,我遇到了一个问题。 现在的方式是,当我在页面加载后向SQL表中添加任何新数据时,div不会刷新包含新数据…只是页面加载表中的数据。

这是我的控制器:

public ActionResult Index() { List<List> result = DataAccess.DataAccess.Read(Build.StringArray("Notifications")); Notifications Notify = new Notifications(); Notify.Update = new List(); foreach (List row in result) { Notification x = new Notification(); x.notificationMessage = (string)row[1]; x.ID = (int)row[0]; x.TimeStamp = (DateTime)row[2]; Notify.Update.Insert(0,x); } return View("Index",Notify); } 

这是我的部分视图:

 @model inConcert.Models.Notifications  @foreach (var item in Model.Update) {  } 

Update

TimeStamp

@item.notificationMessage @item.TimeStamp

索引视图:

 @model inConcert.Models.Notifications     
@Html.Partial("~/Views/Shared/NotificationPartial.cshtml")
$(document).ready(function () { setInterval(function () { $("#notificationsTable").load("~/Views/Shared/NotificationPartial.cshtml"); }, 2000); });

我的模特:

 public class Notification { [Key] public int ID { get; set; } public string notificationMessage { get; set; } public DateTime TimeStamp { get; set; } } public class Notifications : DbContext { public List Update { get; set; } } 

您的.load()函数正在尝试调用一个静态文件,该文件默认会抛出403(Forbidden)错误且没有数据更新(我强烈建议您学习使用浏览器工具 – 这应该是显而易见的)

您需要创建一个生成模型的控制器方法,并返回数据的部分视图。 例如

 public ActionResult Fetch() { Notifications model = new Notifications(); .... // populate your model from the repository return PartialView("_Notifications", model); } 

_Notifications.cshtml

 @model inConcert.Models.Notification @foreach (var item in Model.Update) {  @item.notificationMessage @item.TimeStamp  } 

在主视图中,要初始加载它,您可以使用

 @{Html.RenderAction("Fetch");} 

这意味着您不必在Index()方法中创建和传递模型

然后在脚本中

 var url = '@Url.Action("Fetch")'; var notifications = $("#notificationsTable"); // cache it to avoid repeatedly searching the DOM setInterval(function () { notifications.load(url); }, 2000); 

旁注:除非您期望数据每2秒不断变化,否则这种方法效率可能会非常低。 作为一种改变,您应该考虑使用SignalR,以便您的服务器端代码实时地将内容推送到连接的客户端。 另请参阅本教程 。