Html ASP.Net MVC 4 在表单提交时设置“onsubmit”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28602777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.Net MVC 4 Set 'onsubmit' on form submission
提问by hutchonoid
I have the following form:
我有以下表格:
@Html.BeginForm("ActionMethod","Controller",FormMethod.Post)
On submission I want to run a Javascript function, so I added the following:
提交时我想运行一个 Javascript 函数,所以我添加了以下内容:
@Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "myJsFunction()" })
But, it doesn't work... What am I doing wrong? Thanks!
但是,它不起作用......我做错了什么?谢谢!
回答by hutchonoid
You need this instead:
你需要这个:
@using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "return myJsFunction()" }))
{
//form
}
Notice the using
this makes the form self closing, without the using you need to close it as detailed in this MSDN article.
请注意,using
这会使表单自动关闭,而无需使用此MSDN 文章中的详细说明将其关闭。
You can confirm javascript is called with this to isolate the problem:
您可以确认使用此调用 javascript 以隔离问题:
@using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "alert('test')" }))
{
<input type="submit" value="test" />
}
This should pop up an alert.
这应该会弹出一个警报。
If the first one fails and the second one works, there is a problem with your js script references. This would raise an error in your browser console.
如果第一个失败而第二个有效,则您的 js 脚本引用存在问题。这会在您的浏览器控制台中引发错误。
Update
更新
Instead of binding your form obtrusively, if you give your form an Id you could use the following jquery instead (jQuery reference):
而不是突兀地绑定你的表单,如果你给你的表单一个 Id,你可以使用以下 jquery 代替(jQuery 参考):
@using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { id = "target"}))
{
//form
}
<script>
$(function () {
$("#target").submit(function (event) {
event.preventDefault();
myJsFunction();
});
});
</script>
This would bind when the form when the document is ready.
当文档准备好时,这将绑定表单。