【问题标题】:MVC PartialView is not refreshing dataMVC PartialView 不刷新数据
【发布时间】:2015-03-20 01:56:26
【问题描述】:

我有一个索引页面:

@model AlfoncinaMVC.Models.VentaIndexViewModel

@{
    ViewBag.Title = "Ventas";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script>
    var d = 1;
    setInterval(function () {
        d++;
        $('#testLabe').text(d);
        $.ajax("Ventas");
    }, 1000 * 1 * 1);
</script>

<div id="ventasTable">
    @{ Html.RenderPartial("_VentasTable"); }
    @*@Html.Partial("_VentasTable")*@
</div>

<label id="testLabe"></label>

带有局部视图(_VentasTable):

@model AlfoncinaMVC.Models.VentaIndexViewModel

<table>
    <thead>

    </thead>
    <tbody>
        @foreach (var item in @Model.Ventas)
        {
            <tr>
                <td>
                    @item.nombreArticulo
                </td>
            </tr>
        }
    </tbody>
</table>

使用此控制器:

public ActionResult Ventas()
        {
            var db = new AlfonsinaEntities();
            var ventas = db.Set<Venta>();

            var vm = new VentaIndexViewModel
            {
                Ventas = ventas.Select(x => new VentaViewModel
                {
                    nombreArticulo = x.NombreArticulo
                }).ToList()
            };

            if (Request.IsAjaxRequest())
            {
                return PartialView("_VentasTable", vm);
            }
            return View("Ventas", vm);
        }

在调用 Html.RenderPartial 之后,我无法在局部视图 (_VentasTable) 中刷新数据(也不能使用 HTML.Partial,请注意在我的代码中对此进行了注释。) 在我的局部视图上放置断点后,我看到数据已从数据库查询中更改,但该数据并未在局部视图中被替换。有什么帮助吗?

【问题讨论】:

  • $.ajax("Ventas"); 应该实现什么?阅读api.jquery.com/jquery.ajax
  • 要为@Igor 的评论提供更多上下文,您不能只将ActionResult 的名称提供给jquery 的ajax 调用。那样是行不通的。
  • @Igor 对不起,你的意思是什么?我的呼叫没有任何问题,它正在到达控制器。
  • 你需要阅读@Igor 给你的链接。您需要在success 回调中将返回的数据添加到DOM。 1000 * 1 * 1(总是1000)有什么意义?

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-partialview renderpartial


【解决方案1】:

正如@StephenMuecke 所说——“您需要将返回的数据添加到 DOM”:

$.ajax({
  type: "GET",
  url: '@Url.Action("Ventas", "ControllerName")',
  async: true,
  cache: false,
  dataType: "html",
  success: function (data, textStatus, jqXHR) {
    $("#ventasTable").html(data);
  },
  error: function (jqXHR, textStatus, errorThrown) {
    alert(textStatus + " - " + errorThrown);
  }
});

【讨论】:

  • 建议您使用url: '@Url.Action("Ventas", "ControllerName")', 以确保网址正确。
  • 可能还值得一提的是,脚本应该位于页面底部或包裹在document.ready()
猜你喜欢
  • 2012-07-14
  • 1970-01-01
  • 2013-08-17
  • 2019-02-21
  • 1970-01-01
  • 2019-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多