ASP.Net MVC 4设置&on;#39; onsubmit&#;;提交表格时 [英] ASP.Net MVC 4 Set 'onsubmit' on form submission
问题描述
我的格式如下:
@Html.BeginForm("ActionMethod","Controller",FormMethod.Post)
提交后,我想运行Javascript函数,因此添加了以下内容:
On submission I want to run a Javascript function, so I added the following:
@Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "myJsFunction()" })
但是,这不起作用...我做错了什么?谢谢!
But, it doesn't work... What am I doing wrong? Thanks!
推荐答案
您需要此:
@using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "return myJsFunction()" }))
{
//form
}
请注意,使用 using
可以使表单自动关闭,而无需使用,您需要按照此
Notice the using
this makes the form self closing, without the using you need to close it as detailed in this MSDN article.
您可以确认与此一起调用了javascript,以找出问题所在:
You can confirm javascript is called with this to isolate the problem:
@using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "alert('test')" }))
{
<input type="submit" value="test" />
}
这应该弹出一个警报.
如果第一个失败,而第二个成功,则您的js脚本引用有问题.这会在您的浏览器控制台中引发错误.
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.
更新
Instead of binding your form obtrusively, if you give your form an Id you could use the following jquery instead (jQuery reference):
@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.
这篇关于ASP.Net MVC 4设置&on;#39; onsubmit&#;;提交表格时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!