有条件地取消 ASP.NET MVC 2 表单发布
我试图在表单提交回服务器之前运行一些 JavaScript。在此 javascript 中,我将根据 javascript 函数中的某些验证逻辑来允许或不允许该帖子。我在其他地方读过,为了防止表单发布发生,我需要做的就是从我的 javascript 函数返回 false。我正在下面的代码中尝试,但没有成功。我添加了警报以向自己证明该函数正在被调用。谁能告诉我我做错了什么?
<script type="text/javascript">
function validateOtherAndComment() {
alert("validateOtherAndComment called");
return false;
}
</script>
<h2>Create</h2>
<%
using (Html.BeginForm("Create", "Home", FormMethod.Post,
new
{
onsubmit = "validateOtherAndComment();",
}))
{%>
<%=Html.ValidationSummary(true)%>
<fieldset>
<legend>New Event</legend>
<div class="editor-label">
<%=Html.Label("Comment (max 250)")%>
</div>
<div class="editor-field">
<%=Html.TextArea("commentTextArea", "", 7, 40, new object())%>
<%=Html.ValidationMessage("comment")%>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<%
}%>
I am trying to get some javascript to run before the form is submitted back to the server. In this javascript I will either allow the post or not based on some validation logic in the javascript function. I have read elsewhere that to keep the form post from happening all I need to do is return false from my javascript function. I am trying that in the code below with no luck. I added the alert to prove to myself the function was being called. Can anyone tell me what I am doing wrong?
<script type="text/javascript">
function validateOtherAndComment() {
alert("validateOtherAndComment called");
return false;
}
</script>
<h2>Create</h2>
<%
using (Html.BeginForm("Create", "Home", FormMethod.Post,
new
{
onsubmit = "validateOtherAndComment();",
}))
{%>
<%=Html.ValidationSummary(true)%>
<fieldset>
<legend>New Event</legend>
<div class="editor-label">
<%=Html.Label("Comment (max 250)")%>
</div>
<div class="editor-field">
<%=Html.TextArea("commentTextArea", "", 7, 40, new object())%>
<%=Html.ValidationMessage("comment")%>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<%
}%>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试这样:
注意
return
语句。Try like this:
Notice the
return
statement.