Wednesday, December 21, 2011

How to call Server Side function from Client Side Code

You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds.
1. Use __doPostBack() and IPostBackEventHandler.
2. Set hidden variables and sumbit the form using form.submit()
3. Use PageMethods in ASP.net AJAX.

PageMethods can possibly save you a large amount of bandwidth which can mean faster response times for visitors on slower connections. Instead of posting all of the form values, we can send only what is needed. Instead of returning a large chunk of data, we can return precisely what we need to display to the user. For performance and bandwidth sensitive situations, they may be the right tool. So use PageMethods where possible instead of UpdatePanel as UpdatePanel posts all of the page's form values when all you might need to pass to the server is very little information. Using PageMethods you can save bandwidth.

Here is a link to learn how to use PageMethods: http://www.dotnetcurry.com/ShowArticle.aspx?ID=109

Tuesday, December 20, 2011

Disable a button during postback

You may want to disable a button during postback to stop user from clicking the button before the results are returned. You could do this on the client side using the OnClientClick attribute. The problem with disabling a submit button on the client side is that it will cancel the browser's submit, and thus the postback. Hence your server side event (BtnSumbit_Click) will not trigger.

asp:Button runat="server" ID="BtnSubmit"
OnClientClick="this.disabled = true; this.value = 'Submitting...';"
OnClick="BtnSubmit_Click"
Text="Submit Me!"

The trick is to set the UseSubmitBehavior property to false. This tells .Net to inject the necessary client script to fire the postback anyway, instead of relying on the browser's form submission behavior.

asp:Button runat="server" ID="BtnSubmit"
OnClientClick="this.disabled = true; this.value = 'Submitting...';"
UseSubmitBehavior="false"
OnClick="BtnSubmit_Click"
Text="Submit Me!"

This property will inject __doPostBack giving us this rendered HTML:

input type="button" name="BtnSubmit"
onclick="this.disabled = true; this.value = 'Submitting...';__doPostBack('BtnSubmit','')"