ASP.Net MVC 4在表单提交上设置'onsubmit'

5 html asp.net asp.net-mvc razor asp.net-mvc-4

我有以下表格:

@Html.BeginForm("ActionMethod","Controller",FormMethod.Post)
Run Code Online (Sandbox Code Playgroud)

提交时我想运行Javascript函数,所以我添加了以下内容:

@Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "myJsFunction()" })
Run Code Online (Sandbox Code Playgroud)

但是,它不起作用......我做错了什么?谢谢!

hut*_*oid 11

你需要这个:

@using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "return myJsFunction()" }))
{
        //form
}
Run Code Online (Sandbox Code Playgroud)

请注意,using这使表单自行关闭,无需使用,您需要关闭它,如本MSDN文章中所述.

您可以使用此方法确认调用javascript以隔离问题:

@using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "alert('test')" }))
{
        <input type="submit" value="test" />
}
Run Code Online (Sandbox Code Playgroud)

这应该弹出警报.

如果第一个失败而第二个失败,则js脚本引用存在问题.这会在浏览器控制台中引发错误.

更新

如果你给你的表单一个Id,你可以使用下面的jquery(jQuery引用),而不是突然绑定你的表单:

@using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { id = "target"}))
{
        //form
}

<script>
    $(function () {
        $("#target").submit(function (event) {
            event.preventDefault();
            myJsFunction();
        });
    });
</script>
Run Code Online (Sandbox Code Playgroud)

当文档准备好时,这将在表单时绑定.