ASP.Net MVC 4设置表单提交“的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 = "myJsFunction()" }))
{
//form
}
注意使用
这使得形式的自我封闭,不使用则需要关闭它在本的 MSDN文章
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.
更新
而不是冒失地结合您的窗体,如果你给你的表格,你可以使用下面的jQuery而不是一个ID(的 jQuery的参考 )
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设置表单提交“的onsubmit”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!