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

扩展阅读

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.

https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.button.usesubmitbehavior?view=netframework-4.8

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)的更多相关文章

  1. ASP.NET开发在JavaScript有中文汉字时出现乱码时简单有效的解决

    一般情况在使用ASP.NET开发使用JavaScript有中文汉字时不会出现乱码情况,比如:alert('您看到我了吗?');这样直接输入中文汉字的代码中是不会出现乱码的,如果出现了,一是检查Web. ...

  2. ASP.NET中使用JavaScript实现图片自动水平滚动效果

    参照网上的资料,在ASP.NET中使用JavaScript实现图片自动水平滚动效果. 1.页面前台代码: <%@ Page Language="C#" AutoEventWi ...

  3. [ASP.NET]从ASP.NET Postback机制,到POST/GET方法

    写这篇博客的起源来自于自己最近在学习ASP.NET时对于 PostBack机制的困惑.因为自己在解决困惑地同时,会不断产生新的疑问,因此博客最后深入到了http 包的格式和Internet所使用的TC ...

  4. ASP.NET Core Loves JavaScript

    前言 在 ASP.NET 团队的 Github 的主页上,有这样一个开源项目叫:"JavaScriptsServices",那么 什么是 JavaScriptsServices 呢 ...

  5. asp.net中调用javascript自定义函数的方法(包括引入JavaScript文件)总结

    通常javascript代码可以与HTML标签一起直接放在前 端页面中,但如果JS代码多的话一方面不利于维护,另一方面也对搜索引擎不友好,因为页面因此而变得臃肿:所以一般有良好开发习惯的程序员都会把 ...

  6. Asp.net中前台javascript与后台C#交互

    方法一:使用Ajax开发框架,后台方法定义前添加[AjaxPro.AjaxMethod],然后就可以在前台js脚本中调用后台C#函数. 方法二:后台方法声明为public或者protected,然后前 ...

  7. ASP.NET 中整合JavaScript的技巧

    尽管ASP.NET提供了一个强壮的平台,但是开发者也不应忽视诸如JavaScript这样成熟的技术.在这篇文章中,Tony Patton将向您解释在Web开发中如何将JavaScript与ASP.NE ...

  8. 关于在ASP.NET中使用JavaScript的建议

    一个很恼人的情况,就是当你使用JS在一个ASP,NET应用程序中引用一个在模板页初始化的服务器控件的时候: 比如,我们在模板页有一个TextBox的服务器控件,而且我们想要去获取他的Text:如果你使 ...

  9. asp.ne如何使用javascript去验证客户端信息,如果验证成功则送往服务器端处理,否则在客户端提示用户(不返回到服务器端处理)

    一.问题 在网站一般都有很多地方需要用户去填写一些信息,然后用户点击提交,将信息送往后台储存到数据库中.在这一个过程我以前做法直接在button的click事件中来判断用户输入的数据是否完整和合法,虽 ...

随机推荐

  1. $store.getters调用不执行

    $store.getters调用不执行 api:https://vuex.vuejs.org/zh/guide/getters.html 场景: 在登录时将登录得到的用户信息存储在vuex的state ...

  2. AngularJS 在实际应用中优缺点

    AngularJS 在实际应用中优点:模板功能强大丰富,并且是声明式的,自带了丰富的Angular指令:是一个比较完善的前端MV*框架,包含模板,数据双向绑定,路由,模块化,服务,过滤器,依赖注入等所 ...

  3. win7下CodeIgniter安装

    一.CodeIgniter是什么 CodeIgniter 是一套给 PHP 网站开发者使用的应用程序开发框架和工具包. 它的目标是让你能够更快速的开发,它提供了日常任务中所需的大量类库, 以及简单的接 ...

  4. ip正则

    IP地址是指互联网协议地址(英语:Internet Protocol Address,又译为网际协议地址),是IP Address的缩写.IP地址是IP协议提供的一种统一的地址格式,它为互联网上的每一 ...

  5. 心态炸了,我再写一个4.1.0版本的SND实例

    maven依赖 <!-- Tests --><dependency> <groupId>org.springframework</groupId> &l ...

  6. 如何获取到app的包名

    相信很多朋友在刚开始接触测试app的时候都不清楚app的包名是什么,接下来给大家介绍几种方法去获取. 一.手机设备已连接到电脑,点击进入app中,前提是电脑上装备了android-SDK,tools文 ...

  7. python+openCV实现双目视差图及测距

    通过matlab标定得到相机参数放到stereoconfig.py import numpy as np import cv2 #双目相机参数 class stereoCameral(object): ...

  8. hadoop namenode切换

    hdfs haadmin -transitionToActive --forcemanual nn1 将nn1强制转换为Active hdfs haadmin -transitionToStandby ...

  9. 【leetcode】Trips and Users

    The Trips table holds all taxi trips. Each trip has a unique Id, while Client_Id and Driver_Id are b ...

  10. youtube 上 us的站点是有免费的电影。

    us站点有免费: 菲力宾 跟日本的没有免费的 (PHP是菲力宾币)