Wednesday, October 12, 2011

Sample ASP.NET Ajax Leaky Abstraction

Below is the work-around for problem on non-working ASP.NET UpdateProgress(with AssociatedUpdatePanelID) when the control(e.g. Button) that causes the post-back is outside of the UpdatePanel. This is the cause of the error:

http://stackoverflow.com/questions/1187953/updateprogessbar-is-not-working-when-setting-associatedupdatepanelid


This is the solution for ASP.NET AJAX leaky abstraction :-)

http://stackoverflow.com/questions/996957/why-does-update-progress-does-not-fire-when-associatedupdatepanelid-is-set


An implementation:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="WebApplication7._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <script type="text/JavaScript" language="JavaScript">
        function pageLoad() {
            var manager = Sys.WebForms.PageRequestManager.getInstance();
            manager.add_beginRequest(OnBeginRequest);
        }
        function OnBeginRequest(sender, args) {
            var postBackElement = args.get_postBackElement();
            if (postBackElement.id == 'MainContent_Button1') {
                var up = $get('MainContent_UpdateProgress1');
                up.style.display = "block";
            }
        }
    </script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">
            www.asp.net</a>.
    </p>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Button1" />
        </Triggers>
        <ContentTemplate>
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </ContentTemplate>
    </asp:UpdatePanel>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    <asp:UpdateProgress ID="UpdateProgress1" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
        <ProgressTemplate>
            Loading ...</ProgressTemplate>
    </asp:UpdateProgress>
</asp:Content>


This sort of leaky abstraction on ASP.NET of simulating states in an otherwise stateless protocol is making me embrace MVC+jQuery combo even more.

And someday, you won't get any answer on this type of question on forums, as it will be deemed too localized a few years from now. Five years or more, give or take, most developers will be using MVC+jQuery or node.js+jQuery already, and you will hardly find someone able to answer this ASP.NET type of question.

No comments:

Post a Comment