Search

Custom Search

Saturday, March 8, 2008

Calling Server Side Method with postback in C#

I've been researching for how to call server side methods over the internet but has been frustrated for all I searched was calling server side method without postback using pagemethods or using the ICallBackEventHandler that works like webservice calls in AJAX. I've been pondering time to solve this and found a solutions for myself.

Here is how I did it:
  • Create a linkbutton on design and write an event for this. This event will be called on client side by some javascript function.
  • Register the Server Side Function by using the following:
StringBuilder jscript = new StringBuilder();
jsscript.append("function callServerEvent(){");
jsscript.append(ClientScript.GetPostBackEventReference (LinkButton1, "") + ";}");
RegisterClientScriptBlock("call server", jsscript.ToString());

  • Do this on Page_Load event, then you can now call callServerEvent() from javascript will do a post back and update controls.
  • To hide the control on rendering the page set the display:none on LinkButon's style.
I usually use this in calling server
side function to update controls inside my updatepanel. Using Pagemethods are used for calling static methods and using ICallBackEventHandler is for calling serverside method but with no postback at all.

3 comments:

  1. Hi Vincent,

    I'm not sure if what I'm trying to do is similar to what your saying in this post, or not. But I hope you can help. I'm using StringBuilder in my C# to write out some controls.

    I understand they get written out as HTML. But when one of the links is clicked I need for it to call a C# method.

    How would I do that?

    Thanks,
    Justin

    ReplyDelete
  2. It depends of what kind of method you want to call on the code behind. If the method could be written as static then you can just use PageMethods in javascript then call your static method in C# e.g. PageMethods.Calculate(a,b);

    Or if the method you want to call would require postback you can use the one I post above. Call your method on the linkbutton that we hide and register a javascript function that would call the onclick event of the linkbutton.

    ReplyDelete
  3. yow. sir calaor musta? haha.
    -- adrian pelayo

    ReplyDelete

Adsense Banner