如何在mvc控制器中创建确认框?
我需要在mvc控制器中创建确认框? 使用’yes’或’no’值我需要在我的控制器中执行操作。 我们怎么做?
示例代码:
public ActionResult ActionName(passing value) { // some code message box here if (true) { true code} else { else code} }
您不在Controller中创建确认框,但在View中使用JQuery Dialog创建确认框。 Controller已经在服务器内,因此您没有用户干预。 您的视图,是用户将选择选项,键入信息,单击按钮的位置…您可以截取按钮单击,以显示该对话框,并仅在单击“是”按钮时提交post。 JQuery Dialog需要在页面上引用(jquery.js,jquery-ui.js,jquery.ui.dialog.js)脚本。
例:
$(function(){ $("#buttonID").click(function(event) { event.preventDefault(); $('').dialog({ open: function (event, ui) { $(this).html("Yes or No question?"); }, close: function () { $(this).remove(); }, resizable: false, height: 140, modal: true, buttons: { 'Yes': function () { $(this).dialog('close'); $.post('url/theValueYouWantToPass'); }, 'No': function () { $(this).dialog('close'); $.post('url/theOtherValueYouWantToPAss'); } } }); }); });
您可以使用ActionLink执行此操作
@Html.ActionLink( "Delete", "DeleteAction", "Product", new { confirm = true, other_parameter = "some_more_parameter" }, new { onclick = "return confirm('Do you really want to delete this product?')" })
如果用户确认,则链接参数将传递给控制器操作方法。
public ActionResult DeleteAction(bool confirm, string other_parameter) { // if user confirm to delete then this action will fire // and you can pass true value. If not, then it is already not confirmed. return View(); }
更新
您无法在控制器端显示消息框。 但你可以像下面这样做
public ActionResult ActionName(passing value) { // some code message box here if (true){ ViewBag.Status = true } else { ViewBag.Status = false} return View(); }
并查看
但这些所有代码都不是优雅的方式。 这是你的场景的解决方案。
是的,您可以使用@Html.ActionLink
执行此操作,如AliRızaAdıyahşi所评论。
订阅@Html.ActionLink
的onclick
事件
这是实施:
@Html.ActionLink("Click here","ActionName","ControllerName",new { @onclick="return Submit();"})
并在javascript中写下confirm
框。
编辑
试试这样:
@Html.ActionLink("Submit", "Somemethod", "Home", new { @onclick = "return Submit();", id = "anchortag" })
现在在你的控制器中根据isTrue
查询字符串做一些操作
public ActionResult Somemethod(bool isTrue) { if (isTrue) { //do something } else { //do something } return View(); }
我可以确认AliRızaAdıyahşi的解决方案效果很好。
您还可以自定义消息。 在我的情况下,我们使用MVC和Razor,所以我可以这样做:
@Html.ActionLink("Delete", "DeleteTag", new { id = t.IDTag }, new { onclick = "return confirm('Do you really want to delete the tag " + @t.Tag + "?')" })
其中显示了一个包含其中命名的特定记录的对话框。 也可能给确认对话框一个标题,还没有尝试过。