【问题标题】:Auto refreshing multiple divs MVC自动刷新多个 div MVC
【发布时间】:2016-06-22 08:12:50
【问题描述】:

我想在 MVC 视图中更新表中的一列数据。 这是我要更新的视图。

<table class="table">
<tr>

    <th>
        @Html.DisplayNameFor(model => model.CurrentTemperature)
    </th>

    <th></th>
</tr>
@{int i = 1;}
@foreach (var item in Model)
{
    <tr>
        <td align="center" @*id="@("current"+i)" data-id="@item.ID"*@>
            <div id="@("current"+i)" data-id="@item.ID">
                @{Html.RenderAction("TemperatureUpdateDeviceList", new { idDevice = item.ID });}
            </div>       
        </td>

    </tr>
    i++;
}
</table>

我编写了一个简单的脚本来更新 div。只是为了尝试,我决定只更新 id= current4 的第 4 个 div。

$(function () {

    setInterval(function () {
        var id = $(this).attr('data-id');
            $.ajax({
                url: '@Url.Action("TemperatureUpdateDeviceList")',
                type: 'GET',
                data: { idDevice: id},
            }).success(function (partialView) {
                $('#current4').html(partialView);
            });
    },3000);
});

使用此方法我无法执行正确的请求,因为生成的 URL 不正确。如何获得正确的网址?

注意 TemperatureUpdateDeviceList 函数定义为:

public PartialViewResult TemperatureUpdateDeviceList(int idDevice)
    {            
       return PartialView(temperatureModel);
    }

【问题讨论】:

  • Url.Action() 生成的 url 是什么?您要查找的网址是什么?
  • 您的基本网址是正确的,但您的 id 不会是($(this) 不是元素)。没有必要给你的 div 一个 id 属性。您可以使用类名获取所有 div 并使用 $.each() 循环,您可以在其中使用 $(this).data('id')$(this).html(partialView)
  • 不返回参数:idDevice
  • 除了 Stephens 的正确观察 - js-sn-p 是否放置在启用剃刀的视图中(即不在 js 文件中)?
  • 嗯,js和view在同一个cshtml文件中

标签: javascript jquery ajax asp.net-mvc razor


【解决方案1】:

您使用var id = $(this).attr('data-id'); 不会传递data-id 值,因为$(this) 不是您的&lt;div&gt; 元素。如果要更新所有元素,请将 html 更改为

<div class="container" data-id="@item.ID">
    @{Html.RenderAction("TemperatureUpdateDeviceList", new { idDevice = item.ID });}
</div>

注意id 属性不是必需的。然后在脚本中使用

var url = '@Url.Action("TemperatureUpdateDeviceList")';

setInterval(function () {
    $('.container').each(function() {
        var id = $(this).data('id');
        var div = $(this);
        $.get(url, { idDevice: id}, function(partialView) {
            div.html(partialView);
        });
    });
},3000);

【讨论】:

  • 效果很好!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-02
  • 2011-03-06
  • 1970-01-01
  • 1970-01-01
  • 2012-12-15
相关资源
最近更新 更多