A PageMethod returning a object[] will be the ugliest of solutions, you would say. Sometimes, you are forced to code in a not-so-elegant style. And here's one such implementation. If any of you think you can make it better, please leave a comment.
Another solution to this will be to wrap all these objects up into a class and have this as the return type.
public class MyReturnType { public ClassA A { get;set; } public ClassB B { get;set; } public ClassC C { get;set; } }
and return an instance of MyReturnType (or List for multiple values)
Returning this composite MyReturnType object will be the ideal solution. But in my case, the elements of this class are known only at run time. Typically, this class will need to be build at run time. The easier alternate will be to
[WebMethod] public object[] GetObjects() { ... return new object[] { objA, objB, objC }; }
Asynchronous communication with the server is also made possible by implementing the ICallbackEventHandler interface (System.Web.UI.ICallbackEventHandler). ICallbackEventHandler sends user defined elements back to the server to process and the output is return in the form of a string back to the client, thus enabling a partial postback without the UpdatePanel.
These are the steps in implementing ICallbackEventHandler interface:
Inherit ICallbackEventHandler
Inherit ICallbackEventHandler on the page or the user control where it needs to be implemented. The code for this will be
public partial class Contributions : System.Web.UI.UserControl, ICallbackEventHandler
As a result, two functions needs to be implemented in the code
public void RaiseCallbackEvent(string eventArgument)
public string GetCallbackResult()
RaiseCallbackEvent() is automatically called when there is a Callback event. The GetCallbackResult() is called in sequence right after the RaiseCallbackEvent() is processed.
public string GetCallbackResult()
{
return result;
}
This method here just ejects HTML code into the page to set the server datetime.
public void RaiseCallbackEvent(string eventArgument)
{
result = "document.getElementById('txtPercentage').innerHTML = '" + DateTime.Now.ToLongTimeString() + "'";
}
The method RaiseCallbackEvent() here, just passes the server datetime back to the client. This can typically be any server process and the result variable being set.
ASPX/ASCX page
Below is the HTML for the usercontrol. The Callback, in this case will be initiated from a user control.
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Contributions.ascx.cs" Inherits="Contributions" %>
The above code will just create a CallbackEvent on onclick() event of the HTML button control.
Code File Wireup
The code for the server side OnPageLoad() will be,