从 JavaScript 调用 ASP.NET EventHandler [英] Calling an ASP.NET EventHandler from JavaScript

查看:21
本文介绍了从 JavaScript 调用 ASP.NET EventHandler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个传统的 ASP.NET Web 表单.我们曾经有一个按钮定义如下:

I have a traditional ASP.NET Web Form. We used to have a button defined as follows:

<asp:Button ID="myButton" Runat="server" OnClick="myButton_Click" />

在 .aspx.cs 页面中,我有以下内容:

In the .aspx.cs page, I have the following:

protected void myButton_Click(object sender, EventArgs e)
{
  // Do Stuff
}

然而,现在有人决定使用一个花哨的 JavaScript 框架.基本上,我只有:

However, now someone has decided to use a fancy JavaScript framework. Essentially, I just have:

  <input type="button" id="myButton" onclick="someJSFunction()" />
  <script type="text/javascript">
    function someJSFunction() {
      // Need to execute "myButton_Click" here.
    }
  </script>

我如何从这里在服务器上实际执行我的原始方法?我知道这是一个非常奇怪的问题.我已经简化了代码,试图直接传达我想要完成的事情.有人能告诉我怎么做吗?

How do I actually execute my original method on the server from here? I know this is a very bizarre question. I've simplified the code to try to and be a direct in communicating what I'm trying to accomplish. Can someone please tell me how to do this?

非常感谢!

推荐答案

你可以写在

__doPostBack('<%=myButton.ClientID%>','OnClick');

或者使用 ASP.Net ClientScriptManager 更好、更不容易出错

or a bit better and less error prone use the ASP.Net ClientScriptManager

<%= Page.ClientScript.GetPostBackEventReference(myButton, String.Empty) %>; 

第二个实际上在幕后写了 __doSubmit 但你正在让 ASP.Net 框架为你做这件事.此外,第一个将回发页面,但第二个也会触发正确的服务器端事件.它更好地集成到 ASP.Net 架构中.两者都可以.

The second actually writes __doSubmit under the covers but you are getting the ASP.Net framework to do it for you. Also th efirst one will post back the page but the second triggers the correct server side events as well. It integrates a lot better into the ASP.Net architecture. Either would work though.

最近的SO问题比我能(或者更确切地说是当时)更好地解释了这一切

This recent SO question explains it all far better than I can (or rather did at the time)

这篇关于从 JavaScript 调用 ASP.NET EventHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆