MVC3中使用确认对话框的Actionlink

13

我可以为ActionLink显示确认消息吗?

是否需要使用JavaScript?是否可以不用它实现?

能否给我一些示例?

谢谢。

//I want to make a confirmation message appear before the link opens.
@Html.ActionLink("Checkout and view order list", "Order", "Order")
4个回答

40

通过使用重载方法Html.ActionLink(string linkText, string actionName, string controllerName, object RouteValues, object HtmlAttributes)以及一些JavaScript代码,您可以实现以下功能:

@Html.ActionLink("Checkout and view order list", "Order", "Order", null, new { onclick="return confirm('Are you sure you want to click this link?')" })

这将添加HTML属性onclick,当单击链接时将执行指定的javascript。如果链接上的onclick事件(或表单的提交按钮)返回false,则不会发生操作(跟随链接、发布表单)。confirm(message)函数向用户显示具有指定消息的确认对话框,并根据用户的响应返回true或false。


1

编辑:不要使用这个答案,使用Jim的另一个答案。

您将无法使用 ActionLink - 您需要编写一些JavaScript(例如列在此处中的内容)来弹出确认。您可以使用 Url.Action 生成javascript最终将用于post或get端点的URL。

我的JavaScript很糟糕,但我认为这个想法已经到位:

<a href="javascript:confirmation();">Checkout and view order list</a>

<script>
function confirmation() {
 var answer = confirm("Confirm?")
 if(answer) {
  // Do something here, post or get
  window.location = @Url.Action("Order", "Order");
 }
}
</script>

ActionLink 仍然可以使用,只是它不能单独执行确认操作。 - yoozer8
是的,ActionLink有很多重载(有时候尝试使用正确的重载可能会变得混乱)。由于RouteValues和HtmlAttributes也非常灵活,因此您可以通过ActionLink实现很多功能。 - yoozer8

0

在我的情况下,我有一个已经调用了一个动作的按钮:

<input id="ButtonDelete" type="button" value="Delete Experiment" class="big-nevigation-button" onclick="location.href='@Url.Action("DeleteExperiment", "Experiment", new { experimentId = Model.ExperimentId })'" />

在阅读了Jim的回答后,我将其改为以下内容:

<input id="ButtonDelete" type="button" value="Delete Experiment" class="big-nevigation-button" onclick="if (confirm('Are you sure you want to delete experiment???')) location.href='@Url.Action("DeleteExperiment", "Experiment", new { experimentId = Model.ExperimentId })'" />

它很棒! 谢谢Jim!!


-1

在MVC Core中,我使用了这个,但仍然在JavaScript中。

 <button type="submit"  
  asp-action="Delete" asp-route-id="@Model.Id"
  onclick="return confirm('Are you sure you want to delete?');">
  </button>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接