【问题标题】:MVC: Javascript confirm for delete action not workingMVC:Javascript确认删除操作不起作用
【发布时间】:2013-07-26 07:33:23
【问题描述】:

我对 MVC 和 Javascript 还是很陌生;我正在尝试进行删除操作;我正在使用带有 Javascript 函数的 ActionLink 进行确认。 JAvascript 确认不起作用,即使我按下取消也会触发删除操作;此外,我似乎无法对动作使用 [HttpDelete] 动词:我需要将两个参数传递给 Delete 动作,但在它搜索的动作链接上应用 @Html.HttpMethodOverride(Http.Delete) 之后 对于只有一个参数的 URL:id。

这是我的代码:操作链接

 @Html.HttpMethodOverride(HttpVerbs.Delete)
  @Html.ActionLink(
                "Delete", 
                "Delete", 
                new {id=notification.Id, typeId=notification.TypeId}, 
                new {onclick="confirmDeleteAction()"})

function confirmDeleteAction() {       
    return confirm('Are you sure you want to delete the notification ?');        
}

删除操作:

   [HttpDelete]
    public ActionResult Delete(int id, int typeId)
    {
        Service.DeleteNotification(id, typeId);

        NewIndexViewModel model = Service.GetNewIndexViewModel();
        return View("Index", model);
    }

【问题讨论】:

  • 要将两个参数传递给删除方法,您必须在 Route.config 文件中添加一个条目
  • 如果你想使用动词,请访问blog

标签: javascript asp.net-mvc


【解决方案1】:

试试这个

 @Html.ActionLink(
            "Delete", 
            "Delete", 
            new {id=notification.Id, typeId=notification.TypeId}, 
            new {onclick="return confirmDeleteAction();"})

【讨论】:

  • 成功了,谢谢!只剩下一个问题:使用 HttpDelete 动词时使动作起作用;知道为什么我不能将两个参数传递给与 HttpDelete 动词合并的动作吗?
  • @OctavianEpure 尝试删除动词然后它将在简单的 MVC 中工作
  • 我知道它可以不使用动词,我只是想使用 HttpDelete 动词来避免使用 GET。我在这里找到了一篇文章,解释了安全原因。我也想避免 POST,因为我已经在表单上有一个提交按钮。这是一个复杂的索引视图,可以从中触发多个操作:添加、编辑、删除、存档项目,我不想通过多个发布操作使其过于复杂,也不想使用安全的方式进行删除。否则,我可以使用 GET 删除操作并希望最好:)
【解决方案2】:

当用户点击取消时,您需要取消浏览器的默认行为。您可以通过将confirmDeleteAction() 的结果返回到您的<a> 标签来做到这一点:

@Html.ActionLink(
                "Delete", 
                "Delete", 
                new {id=notification.Id, typeId=notification.TypeId}, 
                new {onclick="return confirmDeleteAction()"})

为了清楚起见,我将 return 关键字添加到您的 onclick 处理程序中,这会将 confirmDeleteAction() 的结果返回给浏览器 -

true = 执行链接的默认行为

false = 什么都不做

【讨论】:

    【解决方案3】:

    你也可以这样做。

    @Html.ActionLink(
                    "Delete", 
                    "Delete", 
                    new {id=notification.Id, typeId=notification.TypeId}, 
                    new {onclick="confirmDeleteAction(" + notification.Id + ")" })
    
    
    function OnDeleteClick(id) {
                        var ActionID = id;
                        var flag = confirm('Are you sure you want to delete this record?');
                        if (flag) {
                    return true;
                    }
            else{
            return false;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 2022-01-18
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      相关资源
      最近更新 更多