MVC中使用内建的HTML辅助方法产生表单元素提交表单与button按钮事件的陷阱
2024-09-25 21:06:40
网站模板页有个登陆的退出按钮,当点击时跳转到登陆页面。
<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"。
另外楼主的原本的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" />
}
最新文章
- JAVA方法03之动手动脑问题解决
- K3数据库表结构
- C#, Java, PHP, Python和Javascript几种语言的AES加密解密实现[转载]
- python 迭代器、生成器、装饰器
- C语言之实现控制台光标随意移动
- C++重载(主要介绍使用友元函数重载)
- 2D游戏编程5&mdash;锁定频率
- 启动tomcat的 startup.bat屏幕一闪而过
- HDU 2209 翻纸牌游戏
- Python基础学习 -- 列表与元组
- 小程序-canvas在IOS手机层级最高无法展示问题
- 如何把你的.net程序打包上传到nuget
- Oracle 12c RAC 安装文档
- dataset数据来源方式两种,页面展示
- Java多线程之wait、notify/notifyAll 详解,用wait 和notifyAll 以及synchronized实现阻塞队列,多线程拓展之ReentrantLock与Condition
- Java Deque 队列 栈
- JSON_FORCE_OBJECT 数字索引数组 强转对象
- 用.NET WebService Studio调试Web Service解决SOAPAction的问题
- Gym-101375C MaratonIME eats japanese food 初始化struct技巧
- Django配置让其他电脑访问网站(包括:修改IP和端口)