ASP.NET postback with JavaScript (UseSubmitBehavior)
ASP.NET postback with JavaScript
Here is a complete solution
Entire form tag of the asp.net page
<form id="form1" runat="server">
<asp:LinkButton ID="LinkButton1" runat="server" /> <%-- included to force __doPostBack javascript function to be rendered --%> <input type="button" id="Button45" name="Button45" onclick="javascript:__doPostBack('ButtonA','')" value="clicking this will run ButtonA.Click Event Handler" /><br /><br />
<input type="button" id="Button46" name="Button46" onclick="javascript:__doPostBack('ButtonB','')" value="clicking this will run ButtonB.Click Event Handler" /><br /><br /> <asp:Button runat="server" ID="ButtonA" ClientIDMode="Static" Text="ButtonA" /><br /><br />
<asp:Button runat="server" ID="ButtonB" ClientIDMode="Static" Text="ButtonB" />
</form>
Entire Contents of the Page's Code-Behind Class
这里需要注意的是,必须给buttonA和buttonB绑定click事件,这样后面在调用theForm.submit();的时候,才会触发。
public partial class Main : Page
{
protected void Page_Load(object sender, EventArgs e)
{
ButtonA.Click += ButtonA_Click;
ButtonB.Click += ButtonB_Click;
} private void ButtonA_Click(object sender, EventArgs e)
{
Response.Write("You ran the ButtonA click event");
} private void ButtonB_Click(object sender, EventArgs e)
{
Response.Write("You ran the ButtonB click event");
}
}
The LinkButton is included to ensure that the __doPostBack javascript function is rendered to the client.
Simply having Button controls will not cause this __doPostBack function to be rendered.
This function will be rendered by virtue of having a variety of controls on most ASP.NET pages, so an empty link button is typically not needed
将Page_Load方法改为如下
protected void Page_Load(object sender, EventArgs e)
{
var value = Request.Form["__EVENTTARGET"];
Console.WriteLine(value); Console.WriteLine(IsPostBack); ButtonA.Click += ButtonA_Click;
ButtonB.Click += ButtonB_Click;
}
在方法中设置断点,会发现总是page_load先触发,然后才触发click事件
What's going on?
Two input controls are rendered to the client:
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
__EVENTTARGET
receives argument 1 of __doPostBack__EVENTARGUMENT
receives argument 2 of __doPostBack
The __doPostBack function is rendered out like this:
第一个参数是控件名字,第二个参数是事件参数
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
As you can see, it assigns the values to the hidden inputs.
When the form submits / postback occurs:
- If you provided the UniqueID of the Server-Control Button whose button-click-handler you want to run (
javascript:__doPostBack('ButtonB','')
, then the button click handler for that button will be run.
前台JavaScript的theForm.submit();运行后,会触发后台绑定的click事件
What if I don't want to run a click handler, but want to do something else instead?
You can pass whatever you want as arguments to __doPostBack
You can then analyze the hidden input values and run specific code accordingly:
通过下面的代码拿到event target,
需要注意的是通过,直接调用javascript:__doPostBack('ButtonA',''),event target才会有数值。
如果是直接点击buttonA的话,虽然也会触发ButtonA_Click,但是获取 Request.Form["__EVENTTARGET"]的时候,是空值
private void ButtonA_Click(object sender, EventArgs e)
{
var value = Request.Form["__EVENTTARGET"];
Console.WriteLine(value);
Response.Write("You ran the ButtonA click event");
}
If Request.Form("__EVENTTARGET") = "DoSomethingElse" Then
Response.Write("Do Something else")
End If
Other Notes
- What if I don't know the ID of the control whose click handler I want to run?
- If it is not acceptable to set
ClientIDMode="Static"
, then you can do something like this:__doPostBack('<%= myclientid.UniqueID %>', '')
. - Or:
__doPostBack('<%= MYBUTTON.UniqueID %>','')
- This will inject the unique id of the control into the javascript, should you wish it
- If it is not acceptable to set
扩展阅读
Doing or Raising Postback using __doPostBack() function from Javascript in Asp.Net
Understanding the JavaScript __doPostBack Function
For this code to work you need to add any web server control on the form except for Button and ImageButton control (I will tell you why later in this article).
__EVENTTARGET is empty on postback of button click
Just add UseSubmitBehavior="False" to your button.
Gets or sets a value indicating whether the Button control uses the client browser's submit mechanism or the ASP.NET postback mechanism.
如果不设置这个属性,想要拦截对应的js。可以注册一个ClientScriptManager.RegisterOnSubmitStatement
private void RegisterFormSubmit()
{
string script = $@"
$.each($("".preview""), function (index, file) {{
console.log($(file).data('data'));
}});
return false;
";
var scriptManager = Page.ClientScript;
var key = "RegisterFormSubmit";
var type = GetType();
if (!scriptManager.IsOnSubmitStatementRegistered(key))
{
scriptManager.RegisterOnSubmitStatement(type, key, script);
}
}
然后会在前端页面看到
<script type="text/javascript">
//<![CDATA[
function WebForm_OnSubmit() {
if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return false;
$.each($(".preview"), function (index, file) {
console.log($(file).data('data'));
});
return false; return true;
}
ASP.NET postback with JavaScript (UseSubmitBehavior)的更多相关文章
- ASP.NET开发在JavaScript有中文汉字时出现乱码时简单有效的解决
一般情况在使用ASP.NET开发使用JavaScript有中文汉字时不会出现乱码情况,比如:alert('您看到我了吗?');这样直接输入中文汉字的代码中是不会出现乱码的,如果出现了,一是检查Web. ...
- ASP.NET中使用JavaScript实现图片自动水平滚动效果
参照网上的资料,在ASP.NET中使用JavaScript实现图片自动水平滚动效果. 1.页面前台代码: <%@ Page Language="C#" AutoEventWi ...
- [ASP.NET]从ASP.NET Postback机制,到POST/GET方法
写这篇博客的起源来自于自己最近在学习ASP.NET时对于 PostBack机制的困惑.因为自己在解决困惑地同时,会不断产生新的疑问,因此博客最后深入到了http 包的格式和Internet所使用的TC ...
- ASP.NET Core Loves JavaScript
前言 在 ASP.NET 团队的 Github 的主页上,有这样一个开源项目叫:"JavaScriptsServices",那么 什么是 JavaScriptsServices 呢 ...
- asp.net中调用javascript自定义函数的方法(包括引入JavaScript文件)总结
通常javascript代码可以与HTML标签一起直接放在前 端页面中,但如果JS代码多的话一方面不利于维护,另一方面也对搜索引擎不友好,因为页面因此而变得臃肿:所以一般有良好开发习惯的程序员都会把 ...
- Asp.net中前台javascript与后台C#交互
方法一:使用Ajax开发框架,后台方法定义前添加[AjaxPro.AjaxMethod],然后就可以在前台js脚本中调用后台C#函数. 方法二:后台方法声明为public或者protected,然后前 ...
- ASP.NET 中整合JavaScript的技巧
尽管ASP.NET提供了一个强壮的平台,但是开发者也不应忽视诸如JavaScript这样成熟的技术.在这篇文章中,Tony Patton将向您解释在Web开发中如何将JavaScript与ASP.NE ...
- 关于在ASP.NET中使用JavaScript的建议
一个很恼人的情况,就是当你使用JS在一个ASP,NET应用程序中引用一个在模板页初始化的服务器控件的时候: 比如,我们在模板页有一个TextBox的服务器控件,而且我们想要去获取他的Text:如果你使 ...
- asp.ne如何使用javascript去验证客户端信息,如果验证成功则送往服务器端处理,否则在客户端提示用户(不返回到服务器端处理)
一.问题 在网站一般都有很多地方需要用户去填写一些信息,然后用户点击提交,将信息送往后台储存到数据库中.在这一个过程我以前做法直接在button的click事件中来判断用户输入的数据是否完整和合法,虽 ...
随机推荐
- 谈谈对this的指向问题
普通函数中:this——window 定时器:this——window 构造函数中:this——当前实例化的对象 事件处理函数:this——事件触发对象
- Redis分布式之前篇
第一篇:初识Redis 一.Redis是什么? Redis 是一个开源(BSD许可)的,使用ANSI C语言编写的,内存中的数据结构存储系统,它可以用作数据库.缓存和消息中间件. 它支持多种类型的数据 ...
- 前端点击下载excel表格数据
<el-button type="primary" @click="downloadChartData" size="mini"> ...
- Nginx安装目录详解
Nginx安装目录详解 1. 查看有关nginx的所有目录列表,输入命令 rpm -ql nginx 可以查看有关nginx目录信息,但是注意 这种命令只能是在基于yum安装的方式才可以. 2. 下 ...
- openstack dashboard开启https
前提条件: 1.基于http的dashboard能正常访问 2.拥有ssl证书 第一步:修改/etc/openstack-dashboard/local_settings 在DEBUG = False ...
- 小黄车ofo法人被限制出境,它究竟还能撑多久?
因为季节的原因,现在正是骑车的好时候,而且北京也开通了一条自行车的专用路.但就是在这么好的时候,我们发现,路边的小黄车却越来越少了,而且它的麻烦还不断! ofo法人被限制出境 6月12日消息,据上海市 ...
- Zookeeper包中,slf4j-log4j12和log4j冲突问题解决
程序启动时会有日志警告 SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/E ...
- oracle 数据库启动停止小结
---登录sqlplus sqlplus /nolog conn / as sysdba shutdown immediate --启动数据库有两种方式 startup 会自动完成重启数据库的所有步 ...
- UvaL-7670 上下界可行费用流
#include <iostream> #include <cstdio> #include <cstring> #include <queue> #d ...
- string::find_last_not_of
#include <iostream>#include <string> using namespace std;int main(){ string s1("abc ...