ASP.Net MVC 4设置&on;#39; onsubmit&#;;提交表格时 [英] ASP.Net MVC 4 Set 'onsubmit' on form submission

查看:52
本文介绍了ASP.Net MVC 4设置&on;#39; onsubmit&#;;提交表格时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的格式如下:

@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.

更新

如果您不给表单加上一个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设置&on;#39; onsubmit&#;;提交表格时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆