Tuesday, June 16, 2009

Calling server side method from client (using javascript)

I didn't know how easy to achieve this until I read the post in this link:
http://disturbedbuddha.wordpress.com/2008/01/08/executing-server-side-code-from-javascript/

The essence is to put the server side logic in a button's OnClick event handler; then use the HTML DOM click() method to raise the OnClick event.

<script type="text/javascript">

function myClientButton_onclick() {

document.getElementById('btn1').click();

}

script>

<asp:Button ID="btn1" runat="server" Text="Original" OnClientClick="alert('abc')" onclick="btn1_Click" />

<input id="myClientButton" type="button" value="Press Me" onclick="return myClientButton_onclick()" />

Note that the HTML DOM click() method also raises btn1's OnClientClick event.

No comments: