【问题标题】:How to load div with jQuery AJAX and setInterval in MVC 5?如何在 MVC 5 中使用 jQuery AJAX 和 setInterval 加载 div?
【发布时间】:2018-11-01 09:04:40
【问题描述】:

我正在使用 jQuery Ajax。我想每 5 秒加载一次我的表的数据。这是我尝试过的,但它不起作用。它不会返回任何错误或结果。

public ActionResult Index()
{
  return View();
}

public PartialViewResult _List()
{
  List<Purchase> model = db.Purchases.ToList();
  return PartialView("_List", model);
}
<div id="loadList"></div>

@section scripts{
  <script>
    $(document).ready(function () {
      setInterval(function () {
        $("#loadList").load("~/Views/Purchases/_List.cshtml");
      }, 3000);
    });
  </script>
}

我想在#loadListdiv中加载的部分视图。

@model IEnumerable<ChocolateFactory.Data.Purchase>

<table class="table">
<tr>
    <th>@Html.DisplayNameFor(model => model.RefNo)</th>
    <th>@Html.DisplayNameFor(model => model.Date)</th>
    <th>@Html.DisplayNameFor(model => model.Amount)</th>
</tr>
@foreach (var item in Model) {
<tr>
    <td>@Html.DisplayFor(modelItem => item.RefNo)</td>
    <td>@Html.DisplayFor(modelItem => item.Date)</td>
    <td>@Html.DisplayFor(modelItem => item.Amount)</td>
</tr>
}
</table>

部分视图在:

~/Views/Purchases/_List.cshtml

【问题讨论】:

  • 您必须传递返回视图的控制器方法的 url,而不是 .load() 函数中的 .cshtml 文件名 - 例如.load("@Url.Action("_List", YourController");
  • @StephenMuecke 我也试过这个。但它不起作用。 #loadList 未在索引视图中加载。
  • $("#loadList").load("@Url.Action("_List", YourController") 工作得很好。您在浏览器控制台中遇到什么错误?而且我们不知道您的_List.cshtml 视图是什么
  • 我更新了问题。它不会返回任何错误。对不起我的英语兄弟。

标签: c# jquery asp.net-mvc html asp.net-mvc-partialview


【解决方案1】:

问题是因为波浪号字符是站点根目录的 Razor 构造。在此之外它无法识别,因此它在您的 JS 代码中不起作用。由于您已将此逻辑置于视图中,因此您可以使用@Url.Content() 在将 URL 输出到 JS 之前对其进行解析:

setInterval(function () {
  $("#loadList").load("@Url.Content("~/Views/Purchases/_List.cshtml")");
}, 3000);

另外请注意,如果您的路由配置正确,那么您可以使用Url.Action(),它会更健壮,例如@Url.Action("_List", "ControllerNameHere");

然而,应该注意的是,每 3 秒向您的服务器发出一个 AJAX 请求并不是一个好主意。它根本无法扩展,并且会导致性能问题。如果您需要保持服务数据和客户端 UI 紧密同步,那么使用服务器发送事件或 WebSocket 会更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多