MVC中使用内建的HTML辅助方法产生表单元素提交表单与button按钮事件的陷阱

2023-02-21,,

网站模板页有个登陆的退出按钮,当点击时跳转到登陆页面。

 <button onclick="logout()" >退出</button>
$("#logOut").click(function () {
location.href = "@Url.Action("Logout", "Account")";
});

然后再某个页面楼主用了HTML辅助方法产生表单元素,代码如下所示:

@Html.BeginForm("ReturnFile", "File", FormMethod.Post, new { id = "exportForm" }))
{
<input type="hidden" id="exportString3" name="exportString3" />
<input type="hidden" id="fileName3" name="fileName3" />
}

如果页面中不存在上面方法产生的form,那么系统时可以正常使用退出按钮,但是,当两者同时出现时,点击按钮事件却一直跳向了form指向的controller。因为在其他页面退出没出现这种问题,所以楼主以为是form的问题。。。

首先开始查询HTML辅助方法产生表单元素,在界面上显示的html代码如下(多了一串System.Web.Mvc.Html.MvcForm)):

<form id="exportForm" method="post" action="/File/ReturnFile">
System.Web.Mvc.Html.MvcForm) {
<input id="exportString" type="hidden" name="exportString">
<input id="fileName" type="hidden" name="fileName">
}
</form>

如果直接使用form元素是又是没有问题。

解决办法1(直接使用html元素):

 <form method="POST" action="@Url.Action("ReturnFile", "File")" id="exportForm" >
<input type="hidden" id="exportString" name="exportString" />
<input type="hidden" id="fileName" name="fileName" />
</form>

下班后查了资料,发现是button没有显示定义type的类型,在不同的浏览器会有不同的属性,所以一定要加type="button"。

type 属性规定按钮的类型。提示:请始终为按钮规定 type 属性。Internet Explorer 的默认类型是 "button",而其他浏览器中(包括 W3C 规范)的默认值是 "submit"。

另外楼主的原本的form引用方法错误,居然没有报错。正确的使用方法如下:

A.使用@Html.BeginForm,@Html.EndForm(自定义id和name),网上说要用Html.EndForm()来关闭</form>表单,但是楼主测试的时候IE和火狐不加也会关闭

  @{ Html.BeginForm("ReturnFile", "File" , new { @id = string.Empty },FormMethod.Post,new { id = "exportForm", name = "exportForm" }); }
{
@Html.Hidden("exportString1")
@Html.Hidden("fileName1")
}
//不加也可
@{Html.EndForm();}

B.常用的用@using方式

 @using (Html.BeginForm("ReturnFile", "File", new { id = "exportForm" }))
{
<input type="hidden" id="exportString" name="exportString" />
<input type="hidden" id="fileName" name="fileName" />
}

MVC中使用内建的HTML辅助方法产生表单元素提交表单与button按钮事件的陷阱的相关教程结束。

《MVC中使用内建的HTML辅助方法产生表单元素提交表单与button按钮事件的陷阱.doc》

下载本文的Word格式文档,以方便收藏与打印。