我有以下表单:
@Html.BeginForm("ActionMethod","Controller",FormMethod.Post)
提交表单时,我想运行一个Javascript函数,因此我添加了以下内容:
@Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "myJsFunction()" })
但是,它不起作用...我做错了什么?谢谢!
我有以下表单:
@Html.BeginForm("ActionMethod","Controller",FormMethod.Post)
@Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "myJsFunction()" })
但是,它不起作用...我做错了什么?谢谢!
你需要用这个代替:
@using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "return myJsFunction()" }))
{
//form
}
注意:using
让表单自闭合,否则您需要按照此MSDN文章中所述进行关闭。
使用此方法可以排除问题来确认JavaScript是否被调用:
@using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "alert('test')" }))
{
<input type="submit" value="test" />
}
这应该会弹出一个警告。
如果第一个失败,第二个成功,则可能是您的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>
当文档ready时,这将绑定表单。
@using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { id = "form1Demo", onsubmit = "return CheckSubmit(event);" })){
//form
}
<script>
function CheckSubmit(e) {
var Name = $("#Name").val();
var Roll = $("#Roll").val();
var Price = $("#Price").val();
if (Name == "" || Roll == "" || Price == "") {
$("#msg").html("Please Enter All Values!");
swal("Validation Error!", "Please Insert All Values", "warning");
return false;
}
return true;
}
</script>