Call ASP.NET function from JavaScript?

后端 未结 20 2210
暗喜
暗喜 2020-11-22 07:21

I\'m writing a web page in ASP.NET. I have some JavaScript code, and I have a submit button with a click event.

Is it possible to call a method I created in ASP with

20条回答
  •  不要未来只要你来
    2020-11-22 08:12

    Well, if you don't want to do it using Ajax or any other way and just want a normal ASP.NET postback to happen, here is how you do it (without using any other libraries):

    It is a little tricky though... :)

    i. In your code file (assuming you are using C# and .NET 2.0 or later) add the following Interface to your Page class to make it look like

    public partial class Default : System.Web.UI.Page, IPostBackEventHandler{}
    

    ii. This should add (using Tab-Tab) this function to your code file:

    public void RaisePostBackEvent(string eventArgument) { }
    

    iii. In your onclick event in JavaScript, write the following code:

    var pageId = '<%=  Page.ClientID %>';
    __doPostBack(pageId, argumentString);
    

    This will call the 'RaisePostBackEvent' method in your code file with the 'eventArgument' as the 'argumentString' you passed from the JavaScript. Now, you can call any other event you like.

    P.S: That is 'underscore-underscore-doPostBack' ... And, there should be no space in that sequence... Somehow the WMD does not allow me to write to underscores followed by a character!

提交回复
热议问题