我有以下表格:
@Html.BeginForm("ActionMethod","Controller",FormMethod.Post)
提交时我想运行一个 Javascript 函数,所以我添加了以下内容:
@Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "myJsFunction()" })
但是,它不起作用...我做错了什么?谢谢!
最佳答案
你需要这个:
@using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "return myJsFunction()" }))
{
//form
}
注意 using
这会使表单自动关闭,如果不使用,您需要关闭它,如 MSDN article 中所述.
您可以确认调用了 javascript 以隔离问题:
@using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "alert('test')" }))
{
<input type="submit" value="test" />
}
这应该会弹出一个警告。
如果第一个失败而第二个成功,则说明您的 js 脚本引用有问题。这会在您的浏览器控制台中引发错误。
更新
如果您为表单提供一个 ID,则可以使用以下 jquery( jQuery reference )代替强制绑定(bind)您的表单:
@using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { id = "target"}))
{
//form
}
<script>
$(function () {
$("#target").submit(function (event) {
event.preventDefault();
myJsFunction();
});
});
</script>
当文档为 ready 时,这将绑定(bind)表单.
关于html - ASP.Net MVC 4 在提交表单时设置 'onsubmit',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28602777/