Search code examples
c#asp.netajaxjsonradajaxmanager

Can a void AjaxManager_AjaxRequest send JSON data back to the browser?


Can AjaxManager_AjaxRequest only modify controls in its UpdatePanels or can it also send back JSON data in the response. Ideally just JSON data.

So in my ascx I have

protected void Page_Load(object sender, EventArgs e)
{
    RadAjaxManager radAjaxManager = RadAjaxManager.GetCurrent(Page);

    if (radAjaxManager != null)
    {
        radAjaxManager.AjaxRequest += AjaxManager_AjaxRequest;
    }

}

private void AjaxManager_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
   // Somehow tweak it so response is just a JSON object.
}

I just inherited some legacy code and this is the fastest way for me to accomplish my aim without creating a web service to do this properly.

Is there anyway to do what I'm asking?


Solution

  • Yeah, this possible. Actually there are exists two available solutions. The first one is to send ajax request with jQuery ajax method (you can access jQuery functionality with $telerik.$). The only lack of this approach is that target server-side method must be static and you can't access page's ViewState as well as server control's properties values. The alternative approach is to use ScriptManager's RegisterDataItem method in AjaxManager_AjaxRequest method to pass JSON-serialized object back to client and get it in Sys.WebForms.PageRequestManager's endRequest event handler on client.

    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <script type="text/javascript">
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
    
        function endRequestHandler(sender, args) {
            var dataItems = args.get_dataItems();
            if (dataItems && dataItems["<%= RadAjaxManager1.UniqueID %>"]) {
                alert(dataItems["<%= RadAjaxManager1.UniqueID %>"].Response);
            }
        }
    </script>
    <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" />
    
    
    void AjaxManager_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
    {
        ScriptManager1.RegisterDataItem(radAjaxManager , new JavaScriptSerializer().Serialize(new { Response = "Hello, RadAjaxManager!" }), true);
    }