将Json数据动态插入到服务器生成的HTML表中

时间:2012-08-29 02:59:13

标签: jquery ajax asp.net-mvc razor

我有一个使用MVC HTML帮助程序的服务器生成内容表,如下所示:

<table>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.TimeLogEntries[0].Description)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.TimeLogEntries[0].StartTime)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.TimeLogEntries[0].EndTime)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.TimeLogEntries[0].Location)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.TimeLogEntries[0].IsBillable)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.TimeLogEntries[0].IsBilled)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.TimeLogEntries[0].Phase)
            </th>
            <th></th>
        </tr>


        @foreach (var item in Model.TimeLogEntries)
        {
            <tr>
                <td>
                    @Html.DisplayFor(model => item.Description)
                </td>
                <td class="no-wrap">
                    @Html.DisplayFor(model => item.StartTime)
                </td>
                <td class="no-wrap">
                    @Html.DisplayFor(model => item.EndTime)
                </td>
                <td>
                    @Html.DisplayFor(model => item.Location)
                </td>
                <td class="no-wrap">
                    @Html.DisplayFor(model => item.IsBillable)
                </td>
                <td class="no-wrap">
                    @Html.DisplayFor(model => item.IsBilled)
                </td>
                <td class="no-wrap">
                    @Html.DisplayFor(model => item.Phase)
                </td>
                <td class="no-wrap">
                    @Html.ActionLink("Edit", "Edit", "TimeLog", new { id = item.TimeLogEntryId }, null) |
            @Html.ActionLink("Delete", "Delete", "TimeLog", new { id = item.TimeLogEntryId }, null)
                </td>
            </tr>
        }
    </table>

我希望能够使用jQuery向服务器生成的表添加,更改和删除行,但是我应该如何知道HTML帮助程序生成的HTML内容?我已经在返回Json的控制器上编写了动作,但我需要知道如何在客户端进行格式化。在我的JavaScript代码中复制HTML模板似乎是非常糟糕的做法。

1 个答案:

答案 0 :(得分:0)

您可以将表放在局部视图中。定义一个返回局部视图的Action。

你可以在删除函数后调用通过jquery返回部分视图的动作。

$.ajax({
         url: '/ActionThatReturnsPartialView',
         cache: false,
         type: 'post'
         success: function (data) {
             $('#tableID').replaceWith(data);
         },
         error: function (e) {
             alert(e.responseText);                            
         }
});