Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

c# - Calling an ASP.NET EventHandler from JavaScript

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" />

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

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

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?

Thank you so much!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could write in

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

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

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

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...