Calling an ASP.NET EventHandler from JavaScript(从 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 JavaScript 调用 ASP.NET EventHandler
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01