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 JavaScript's click event?
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 JavaScript's click event?
The
__doPostBack()
method works well.Another solution (very hackish) is to simply add an invisible ASP button in your markup and click it with a JavaScript method.
From your JavaScript, retrieve the reference to the button using its ClientID and then call the .click() method on it.
Please try this:
ddlVoucherType is a control which the selected index change will call... And you can put any function on the selected index change of this control.
It is so easy for both scenarios (that is, synchronous/asynchronous) if you want to trigger a server-side event handler, for example, Button's click event.
For triggering an event handler of a control: If you added a ScriptManager on your page already then skip step 1.
Add the following in your page client script section
Write you server side event handler for your control
protected void btnSayHello_Click(object sender, EventArgs e) { Label1.Text = "Hello World..."; }
Add a client function to call the server side event handler
function SayHello() { __doPostBack("btnSayHello", ""); }
Replace the "btnSayHello" in code above with your control's client id.
By doing so, if your control is inside an update panel, the page will not refresh. That is so easy.
One other thing to say is that: Be careful with client id, because it depends on you ID-generation policy defined with the ClientIDMode property.
This is the library called AjaxPro which was written an MVP named Michael Schwarz. This was library was not written by Microsoft.
I have used AjaxPro extensively, and it is a very nice library, that I would recommend for simple callbacks to the server. It does function well with the Microsoft version of Ajax with no issues. However, I would note, with how easy Microsoft has made Ajax, I would only use it if really necessary. It takes a lot of JavaScript to do some really complicated functionality that you get from Microsoft by just dropping it into an update panel.
If anyone else is like Merk, and having trouble over coming this, I have a solution:
When you have a user control, it seems you must also create the PostBackEventHandler in the parent page. And then you can invoke the user control's PostBackEventHandler by calling it directly. See below:
Where UserControlID is the ID you gave the user control on the parent page when you nested it in the mark up.
Note: You can also simply just call methods belonging to that user control directly (in which case, you would only need the RaisePostBackEvent handler in the parent page):
If the __doPostBack function is not generated on the page you need to insert a control to force it like this: