Search code examples
c#asp.net-mvcasp.net-mvc-4asp.net-mvc-partialviewrenderpartial

MVC PartialView is not refreshing data


I have an index page:

@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>

With a partial view (_VentasTable):

@model AlfoncinaMVC.Models.VentaIndexViewModel

<table>
    <thead>

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

With this controller:

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);
        }

And i can NOT get the data to refresh in the partial view (_VentasTable) after the Html.RenderPartial it's being called, (NOT also with HTML.Partial, please note that is commented in my code.) After putting a breakpoint on my partial view i see that the data is CHANGED from the DB query, but this data is not being replaced in the partial view. Any help please?


Solution

  • As @StephenMuecke said - "You need to add the returned data to the 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);
      }
    });