如何从MVC中的表中删除记录

时间:2018-08-21 00:53:48

标签: jquery asp.net-mvc

我想从表中删除记录,然后在MVC中更新表。目前,我可以从表中删除记录,但是表未更新。我编写了脚本来更新部分记录,但是我的脚本没有命中。

请建议我该怎么做?

父视图

 <div class="col-md-2">
            @using (Html.BeginForm("HorseTracker", "HorseTracker", FormMethod.Post, new { @id = "CreateForm" }))
            {
                <div class="panel panel-default">

                    <div class="panel-body">
                        <div class="form-group">

                            @Html.LabelFor(m => m.HorseName, new { @class = "label-control" })
                            @Html.HiddenFor(m => m.HorseId)
                            @Html.TextBoxFor(m => m.HorseName)                       
                        </div>
                        <input type="submit" value="Save" class="btn btn-primary" />
                    </div>
                </div>

            }
        </div>

        <div id="partial" class="col-md-8">

局部视图

<div class="panel panel-default">

    <div class="panel-body">
        <table class="table">
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.HorseName)
                </th>

                <th>
                    @Html.DisplayName("Action")
                </th>

            </tr>

            @foreach (var item in Model)
            {
                <tr>
                    <td class="hidden">
                        @item.HorseId
                    </td>

                    <td>
                        @item.HorseName
                    </td>


                    <td>                      
                        @Ajax.ActionLink("Delete", "Delete", "HorseTracker", new {TrackerId = @item.TrackerId, AccId=item.AccId,UserId=item.UserId, @id = "DeleteRecord" }, new AjaxOptions
                   {
                       HttpMethod = "Post",
                       Confirm = "Are you sure you want to delete this record?"
                   }, null)                
                    </td>
                </tr>
            }

        </table>

    </div>
</div>

控制器方法

[HttpPost]
public PartialViewResult Delete(int TrackerId, int AccId, int UserId)
{
         ClsHorseTracker model = new ClsHorseTracker();
        var username = User.Identity.Name;
        var user = context.Users.SingleOrDefault(u => u.UserName == username);
        model.AccId = user.AccountID;
        model.UserId = user.Id;
        horseTrackerDetails.HorseTrackerDelete(TrackerId);

   return PartialView("_pHorseTrackerDetails", horseTrackerDetails.HorseTrackerList(model));
}

脚本

 $(document).ready(function () {
        var url = '@Url.Action("Delete", "HorseTracker")';
        $(document).click('#DeleteRecord', function () {
            debugger;
              if (!$(this).valid()) {
                return;
            }
              $.post(url, $(this).serialize(), function (response) {
                  if (response) {
                      debugger;
                      $('#partial').html(response);
                      $('#CreateForm').get(0).reset();
                  }
              });
               return false;
           })
    })

1 个答案:

答案 0 :(得分:2)

您的代码存在多个问题。列举一些

  1. 您有多个具有相同id属性的链接,即 无效的html
  2. 您使用Ajax.AcionLink(),然后将其取消并使用$.post() 提交(没有任何意义)
  3. 链接不是表单,因此请选中if (!$(this).valid()) { 没有道理
  4. 您没有将任何数据发送到POST方法($(this).serialize() 正在序列化不包含任何形式的<a>元素 控制,因此无需序列化)

没有理由返回更新表的部分视图(这样做的不必要的额外开销)。相反,如果Delete操作成功(通过返回JsonResult发出信号),只需删除与链接关联的行。

将循环代码更改为

@foreach (var item in Model)
{
    <tr>
        <td class="name">@item.HorseName</td>
        <td><a href="#" class="delete" data-id="@item.TrackerId">Delete</a></td>
    </tr>
}

并添加以下脚本

var url = '@Url.Action("Delete", "HorseTracker")';
$('.delete').click(function() {
    var id = $(this).data('id');
    var row = $(this).closest('tr');
    var name = row.find('.name').text();
    if (window.confirm('Are you sure you want to delete ' + name + '?')) {
        $.post(url, { id: id }, function(response) {
            if (response) {
                row.remove(); // remove the row from the DOM
            }
        }).fail(function(response) {
            .... // an exception was thrown on the server (display error message?)
        });
    }
});

然后将POST方法修改为

[HttpPost]
public PartialViewResult Delete(int id)
{
    horseTrackerDetails.HorseTrackerDelete(id);
    return Json(true);
}