Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 403
Dynde Avatar asked Jan 14 '11 12:01

Dynde


1 Answers

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>
like image 158
A_Nabelsi Avatar answered Nov 05 '22 10:11

A_Nabelsi