2016-08-05 85 views
1

我创建了一个基于解决方案here的多键表单。ASP MVC多按钮表单让JQuery拦截按钮单击

我需要jQuery拦截按钮的单击事件之一,并用模态对话框提交后手动提交。但是,当我尝试使用type =“button”时,控制器中的命令值变为null。我也尝试在我的JavaScript文件中使用preventDefault(),但是同样的事情发生。

笔者认为:

<input id="action1" type="submit" name="command" value="Action One" /> 
<input id="action2" type="submit" name="command" value="Action Two" /> 

在我的控制器:

if (command == "Action One") 
{ 
    // Do something 
} 
else if (command == "Action Two") 
{ 
    // Do something else 
} 

在我的javascript:

$('#action1').click(function (e) { 
    e.preventDefault(); 
    showModalDialog(); 
}); 

回答

1

作为一种变通方法,您可以尝试folloing:

  1. 将相同的CSS class属性分配给两个按钮。
  2. type="button"代替type="submit"
  3. 添加一个jQuery单击事件到css名当两个按钮都将触发clicked.Store在变量
  4. 显示模式弹出,并在用户点击后,点击的按钮值“OK”召控制器操作通过点击按钮的值。

听起来像很多工作,但它非常简单。只需将以下代码复制并粘贴到您的解决方案中并运行它。了解它是如何工作的并适用于您自己的解决方案。

查看:

<head> 
    <meta name="viewport" content="width=device-width" /> 
    <title>Command</title> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script> 
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> 
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> 
    <script type="text/javascript"> 
     $(function() { 
      var command = ""; 

      $(".command").click(function() { 
       command = $(this).val(); 
       $(".modal-body").empty(); 
       $(".modal-body").html("You selected command - " + command + ".Press OK call the controller..."); 
       $('#myModal').modal('show'); 
      }); 

      $("#btnOK").click(function() { 
       $.getJSON("/Command/MyCommand?command=" + command, function (data) { 
        alert(data); 
       }); 
      }); 
     }); 
    </script> 
</head> 
<body> 
    <input class="command" type="button" id="action1" name="command" value="Action One" /> 
    <input class="command" type="button" id="action2" name="command" value="Action Two" /> 
    <div id="myModal" class="modal fade"> 
     <div class="modal-dialog"> 
      <div class="modal-content"> 
       <div class="modal-header"> 
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> 
        <h4 class="modal-title" id="myModalLabel">Modal Header</h4> 
       </div> 
       <div class="modal-body"> 
       </div> 
       <div class="modal-footer"> 
        <button id="btnOK" type="button" class="btn btn-primary" data-dismiss="modal">OK</button> 
        <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button> 
       </div> 
      </div> 
     </div> 
    </div> 
</body> 

控制器:

public class CommandController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    public JsonResult MyCommand(string command) 
    { 
     System.Diagnostics.Debugger.Break(); 
     return Json(command + " is complete.", JsonRequestBehavior.AllowGet); 
    } 
} 
+0

感谢丹尼斯。我会尝试你的解决方案。 –