我根据找到的解决方案here创建了一个多按钮表单。
我需要jQuery拦截其中一个按钮的点击事件,并在显示模态对话框后手动提交。但是,当我尝试使用type =“button”时,控制器中command的值变为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();
});
答案 0 :(得分:1)
作为一种解决方法,您可以尝试以下方法:
class
属性。 type="submit"
替换为type="button"
。css
名称,当点击两个按钮中的任何一个时,该事件将触发。存储变量中单击的按钮值听起来好像很多工作,但它非常简单。只需将下面的代码复制并粘贴到您的解决方案中并运行它。了解它的工作原理并应用于您自己的解决方案。
查看:强>
<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">×</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);
}
}