在从网格中删除记录时显示确认消息

时间:2015-07-03 10:00:03

标签: c# jquery asp.net asp.net-mvc asp.net-mvc-4

我想在用户从网格中删除记录时显示确认消息,这是我实现的但是我有错误消息

使用下面的代码删除记录但是:

  1. 仍然在网格中的记录我必须刷新才能看到它消失;
  2. 我有消息错误!即使删除了记录 3。

     @Html.ActionLink("Delete Student", "Delete", new { @StudentID = StudentID }, new { @class="glyphicon glyphicon-pencil", @id=StudentID })
    
    $(document).ready(function () {
    
        $('a.delete').click(OnDeleteClick);
    
    });
    
    function OnDeleteClick(e)
    { 
        var StudentId = e.target.id; 
        var flag = confirm('You are about to delete this record permanently. Are you sure you want to delete this record?');
    
        if (flag) { 
            $.ajax({
                url: '/Home/DeleteRecord',
                type: 'POST', 
                data: { StudentID: StudentId },
                dataType: 'json', 
                success: function (result) { 
                       alert(result); 
                       $("#" + StudentId).parent().parent().remove(); 
                       },
                error: function () { 
                       alert('Error!'); 
                       }
            });
        }
        return false;
    }
    
  3. 控制器:

        public ActionResult DeleteRecord(string StudentID)
        {
           //Code to delete
            }
            return RedirectToAction("StudentGrid",
                         "Home");
        }
    

2 个答案:

答案 0 :(得分:0)

如果没有看到您正在使用的网格,请尝试以下方法:

获取最近的tr标记,以便您可以在成功时删除它:

var $tr = $(this).closest("tr");
$tr.remove();

<强> jsFiddle

从控制器设置内容消息,重定向将无法正常工作,因为它是一个ajax调用。

 public ActionResult DeleteRecord(string StudentID)
 {
    var success = false;
    //Code to delete
    // then set success variable
    if (success)
    {
        return Content("Deleted");
    }
    else
    {
        return Content("Failed");
    }          
 }

然后从您的成功处理程序检查消息并删除,如果需要,客户端代码最终会像这样:

function OnDeleteClick(e)
{ 
    e.preventDefault();
    var $tr = $(this).closest("tr");  
    var StudentId = e.target.id; 
    var flag = confirm('You are about to delete this record permanently. Are you sure you want to delete this record?');

    if (flag) { 
        $.ajax({
            url: '/Home/DeleteRecord',
            type: 'POST', 
            data: { StudentID: StudentId },
            dataType: 'json', 
            success: function (result) { 
                   if (result == "Deleted")
                        $tr.remove();  
                   },
            error: function () { 
                   alert('Error!'); 
                   }
        });
    }
    return false;
}

答案 1 :(得分:0)

   public ActionResult DeleteRecord(string StudentID)
    {
        //Code to delete
    }
     return Json("Record Is Delete", JsonRequestBehavior.AllowGet); 
    }

有来自控制器的响应你可以在alert()中显示这个MSG 使用项目中的更新网格,您可以使用下面的代码就足够了

$(e).closest("tr").remove();