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. 常用CSS代码大全(工作必备)

    用html+css可以很方便的进行网页的排版布局,但不是每一种属性或者代码我们都铭记于心,最近我把CSS中的常用代码进行了归纳总结,方便自己以后查看,同时也分享给大家,希望对你们有用. 一.文本设置 ...

  2. 富文本编辑器--引入demo和简单使用

    wangEditor —— 轻量级 web 富文本编辑器,配置方便,使用简单.支持 IE10+ 浏览器. 官网:www.wangEditor.com 文档:www.kancloud.cn/wangfu ...

  3. orcle_day02

    第三章:单值函数 函数分为: 1.单值函数 1.字符函数 2.日期函数 3.转换函数 4.数字函数 2.分组函数(后面的章节再做学习) 哑表dual dual是一个虚拟表,用来构成select的语法规 ...

  4. SSD学习笔记

    目标检测算法——SSD:Single Shot MultiBox Detector,是一篇非常经典的目标检测算法,十分值得阅读和进行代码复现,其论文地址是:https://arxiv.org/abs/ ...

  5. k8sIngress资源

    k8s提供了两种内建的云端负载均衡机制用于发布公共应用,一种是工作于传输层的service资源,它实现的是TCP负载均衡器,另一种是Ingress资源,它实现的是HTTP(S)负载均衡器. 1)TCP ...

  6. java web课堂测试

    下面是web界面 <%@ page language="java" import="java.util.*" pageEncoding="UTF ...

  7. chomd添加权限

    chmod 777 -R * 的意思是把当前目录所有文件(递归的)的属性全部为7

  8. mysql更改列属性的一些用法

    更改mysql 主键属性 alter table rbac_auth change column id id int auto_increment

  9. 【Linux学习一】命令行CLI、BASH的基本操作

    ●操作系统的基本结构 操作系统的基本结构通过Kernel(内核)和Shell(壳)构成.常见的Shell分为GUI和CLI GUI 图形方面的shell ------〉windows .mac osC ...

  10. 面向对象之封装 及@property装饰器使用

    目录 封装 1.封装的定义 2.封装的目的: 3.封装的三种方式 4.封装的优点 5.访问限制(封装) @property 装饰器 属性property底层实现 封装 1.封装的定义 将复杂的丑陋的, ...