Dynde
Dynde

Reputation: 2674

Returning values from code to asp.net ajax endrequest

Basically, I have an asp.net ajax enabled usercontrol, and now I'd like to just return a simple string value, to be used in some js I'm firing after the ajax request is done.

I've been fiddling around with the endrequest method, which I already set up to use for exception handling, which works fine. But is there no way to simply return a string value?

First I thought I could do this through Response.Write(); but args.get_response() doesn't like when you do that apparantly - can anyone point me in the right direction?

Thanks!

Upvotes: 7

Views: 5377

Answers (2)

Antonio Bakula
Antonio Bakula

Reputation: 20693

Maybe I don't understand your problem, but what usercontrol had to do with that additional js calls ? You are just rendering that js from user control ?

Anyway, IMO You should use ASP.NET Web Handler (*.ashx) or HttpHandler to return string value and call that handler with that additional js.

Upvotes: -1

A_Nabelsi
A_Nabelsi

Reputation: 2574

You can use the ScriptManager.RegisterDataItem method with the Sys.WebForms.PageRequestManager. Consider the following test page which when you click the button it registers data item with the script manager and at the client side it handles the endrequest and get that data item,

<%@ Page Language="C#" AutoEventWireup="true" Inherits="WebApplication1._Default" %>

<script runat="server">
    protected void btTest_Click(object sender, EventArgs e)
    {
        ScriptManager1.RegisterDataItem(btTest, "Your value to pass to the client");
    }
</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="upTest" runat="server">
            <ContentTemplate>
                <asp:Button ID="btTest" runat="server" Text="Click Me" OnClick="btTest_Click" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
<script language="javascript" type="text/javascript">
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);

    function endRequestHandler(sender, args) {
        var dataItems = args.get_dataItems()['<%= btTest.ClientID %>'];
        if (dataItems != null)
            alert(dataItems);
    }
</script>
</html>

Upvotes: 11

Related Questions