在Html.BeginForm的onsubmit参数中使用return的目的是什么?

问题描述 投票:0回答:1

在一个ASP.NET MVC razor视图中,我在点击按钮时提交一个表单。如果我在onsubmit参数中使用'return',它的表现与不使用'return'不同。

所以,如果我把BeginForm的参数设置成下面的样子。

Html.BeginForm("", "", FormMethod.Post, new { id = "myForm", onsubmit = "return doAction();", @class = "well" })

它的表现与下面的不同。

Html.BeginForm("", "", FormMethod.Post, new { id = "myForm", onsubmit = "doAction();", @class = "well" })

那么使用return或不使用它的目的是什么?

javascript asp.net-mvc html-helper html.beginform
1个回答
2
投票
onsubmit = "doAction();"

doAction(){
   alert("Hello World!");
}

^这样做只是执行你的函数,而且由于... ... doAction() 并没有阻止事件进行默认处理,表单会提交。


onsubmit = "return doAction();"

doAction(){
   alert("Hello World!");
   return false; // form will not submit
   // return true; // form will submit
}

^ 这样做的目的是执行你的函数,如果你的函数返回一个 false 布林值,它将阻止表单的提交。


要想知道它们到底哪里不同,请尝试 onsubmit="doAction()" 和一个函数,返回 false;

onsubmit = "doAction();"

doAction(){
   alert("Hello World!");
   return false; // the form will still submit
}

表格仍然会提交,因为你没有在表格上注明 return 关键字,尽管函数返回 false. 该 return 关键字会发出信号,让表单先检查函数返回的值。

© www.soinside.com 2019 - 2024. All rights reserved.