Click here to Skip to main content
15,892,674 members
Articles / Programming Languages / C#
Tip/Trick

How to enable partial rendering with the AJAX UpdatePanel

Rate me:
Please Sign up or sign in to vote.
5.00/5 (7 votes)
19 Sep 2013CPOL3 min read 60.5K   1.6K   7   6
UpdatePanel tutorial.

Question

Q) How to enable partial rendering with the Ajax UpdatePanel?

Answer

When you use any server side control that do PostBack whole page get refresh.

Some time you want only part of the page get refresh instead of refreshing complete page that avoid flickering of the page and only part of the page flicker call partial rendering.

You can enable partial rendering using ajax UpdatePanel control.

Enabling partial rendering on page is two step process.

Setp1 Drag and drop ScriptManager control on the page inside from tag.

XML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
    
    </div>
    </form>
</body>
</html> 

In case of master page if you want script manager control to affect all the page using master page you can drag and drop script manager on master page inside from tag

XML
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="UpdatePanelDemo.SiteMaster" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>  

If you want to restrict ScriptManager user to page only you can simply drag and drop the control on the page inside body content.

ASP.NET
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager> 

Setp2 Add the section that you want to partial rendering inside the AJAX UpdatePanel ContentTemplate tag. Set the UpdateMode property of ajax panel to <code><code>C<code>onditional.

Note Update mode property of ajax update panel is by default set to AllWays. Allwasys indicate that ajax panel will update for every PostBack same like PostBack without update panel. If we set it to conditional page will update if following three conditions are true.

1) If a control within the updatepanel causes postback.

2) If a trigger on the updatepanel updates.

3) If someone calls "Update()" on the updatepanel itself.

Condition 1 If a control within the updatepanel causes postback.

I have added two update panel. Both are have update mode set to conditional.

Both update panel contain button and DateTime.Now property inside them.

DateTime.Now give current date and time.

When you click on the button1 indide UpdatePanel1 only that update panel get update himself as that of control within the UpdatePanel is causes PostBack where second update panel datetime remain unaffected.

IF you hit on the UpdatePanel2 update button only UpdatePanel2 DateTime get affected as that of control within the UpdatePanel is causes PostBack.

ASP.NET
<!-- Condition1 -->
    <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
    <ContentTemplate>
         <%=DateTime.Now %><asp:Button ID="Button1" runat="server" 
             Text="Condition One" />
    </ContentTemplate>
    </asp:UpdatePanel> 
 <asp:UpdatePanel ID="UpdatePanel2" UpdateMode="Conditional"  runat="server">
    <ContentTemplate>
        <%=DateTime.Now %><asp:Button ID="Button2" runat="server" 
            Text="Condition One" />
    </ContentTemplate>
    </asp:UpdatePanel> 

Condition 2 If a trigger on the updatepanel updates.

Like ContentTemplate update panel have Triggers tag. Triggers tag define trigger to UpdatePanel.

Inside the Triggers tag we need to define AsyncPostBackTrigger control.

AsyncPostBackTrigger have two property ControlID and EventName.

ControlID define control Id of control that trigger UpdatePanel update.

EventName event name of the control that trigger UpdatePanel update.

Lets put DateTime.Now property inside UpdatePanel , ControlID set to button3 and EventName set to Click.

ASP.NET
<!-- Condition2 -->
    <asp:UpdatePanel ID="UpdatePanel3" UpdateMode="Conditional" runat="server">
    <ContentTemplate>
         <%=DateTime.Now %>
    </ContentTemplate>
    <Triggers>
     <asp:AsyncPostBackTrigger ControlID="Button3" EventName="Click" />
    </Triggers>
    </asp:UpdatePanel>
    <asp:Button ID="Button3" runat="server" Text="Condition Two" /> 

Only the content inside the UpdatePanel3 get updated by clicking on Button3 as trigger on the UpdatePanel updates.

Condition 3 If someone calls "Update()" on the UpdatePanel itself.

Lets Add UpdatePanel4 having DateTime.Now property and button added inside the ContentTemplate of UpdatePanel.

We have notice that on button click inside update panel only the update panel with button click get update because of condition 1.

But now in click event of button click we will set the UpdatePanel1.Update().

XML
<!-- Condition3 -->
    <asp:UpdatePanel ID="UpdatePanel4" UpdateMode="Conditional"  runat="server">
    <ContentTemplate>
        <%=DateTime.Now %>
        <asp:Button ID="Button4" runat="server" Text="Condition Three"
            onclick="Button4_Click" />
    </ContentTemplate>
    </asp:UpdatePanel>
C#
protected void Button4_Click(object sender, EventArgs e)
    {
        UpdatePanel1.Update();
    }

We will observe that both the UpdatePanel1 and UpdatePanel4 content get updated as we call calls "Update()" on the UpdatePanel itself.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Lionbridge
India India
Amey K Bhatkar, a “Microsoft .Net” Web Developer.
I am programmer by will and profession.
I have completed my MCA in 2011 and join software industry.
Presently I am working with Lion Bridge Technologies in Mumbai - India

Comments and Discussions

 
QuestionPartial Page Updates not working with Dynamically Created Listboxes and FineUploader Pin
brown7157618-Feb-16 9:28
brown7157618-Feb-16 9:28 
I am using the FineUploader plugin and once you upload an image and then select things from a listbox that are generated dynamically, the Images disappear from the FineUploader list. Any way I can fix this

ASP.NET
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="CreateListing.aspx.cs" Inherits="BazaarOfCards.Members.CreateListing" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
    <link href="../Scripts/fineuploader/fine-uploader-new.css" rel="stylesheet" type="text/css"/>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <div class="Column12" id="Form_NewListing">
       
                <h2 class="h2row">Create Your Listing</h2>

            <div class="wrapper">
                <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" ></asp:ScriptManager>                
                <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">                    
                    <ContentTemplate>   
  
                           <asp:Panel runat="server" ID="pnlContainer" style="display: inline;"></asp:Panel>
                           <asp:Image ImageUrl="~/Images/Selected.png" runat="server" style="display:inline;" ID="ImageSelected" Visible="false"/>


                           <h3 class="h3row">Help buyers find your item with a great title</h3>
                           <ul>
                           <li>
                           <asp:TextBox cssClass="panel" ID="tbTitle" runat="server" height="16px" size="30"  MaxLength="80" TextMode="SingleLine" width="400px"></asp:TextBox>
                           </li>
                           </ul>

                           <h3 class="h3row">Increase chances of selling your item with a great description</h3>
                            <ul>

                        <li>
                            <asp:TextBox cssClass="panel" ID="tbDescription" runat="server" height="400px" TextMode="MultiLine"></asp:TextBox>
                        </li>
                    </ul>   


                    </ContentTemplate> 
                </asp:UpdatePanel>


                <h3 class="h3row">Make sure you show off your item with pictures (Required to have at least 1 image)</h3>
                           <ul>
                              
                            <li>
                            

                               
    <!-- The element where Fine Uploader will exist. -->
    <asp:UpdatePanel ID="UpdatePanel2"  UpdateMode="Conditional" runat="server"> 
    <ContentTemplate>
    <div id="fine-uploader">
    </div>
    
    
    <!-- Fine Uploader -->
    <script src="../Scripts/fineuploader/fine-uploader.min.js" type="text/javascript"></script>

    
    <script type="text/template" id="qq-template">
    
    
        <div class="qq-uploader-selector qq-uploader" qq-drop-area-text="Drop files here">
            <div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container">
                <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div>
            </div>
            <div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
                
            </div>
            <div class="qq-upload-button-selector qq-upload-button">
                <div>Upload a file</div>
            </div>
            
                <span>Processing dropped files...
                
            </span>
            <ul class="qq-upload-list-selector qq-upload-list" aria-live="polite" aria-relevant="additions removals">
                <li>
                    <div class="qq-progress-bar-container-selector">
                        <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-progress-bar-selector qq-progress-bar"></div>
                    </div>
                    
                    <img class="qq-thumbnail-selector" qq-max-size="100" qq-server-scale>
                    
                    
                    <input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
                    
                    <button class="qq-btn qq-upload-cancel-selector qq-upload-cancel">Cancel</button>
                    <button class="qq-btn qq-upload-retry-selector qq-upload-retry">Retry</button>
                    <button class="qq-btn qq-upload-delete-selector qq-upload-delete">Delete</button>
                    <span role="status" class="qq-upload-status-text-selector qq-upload-status-text"></span>
                </li>
            </ul>

            <dialog class="qq-alert-dialog-selector">
                <div class="qq-dialog-message-selector"></div>
                <div class="qq-dialog-buttons">
                    <button class="qq-cancel-button-selector">Close</button>
                </div>
            </dialog>

            <dialog class="qq-confirm-dialog-selector">
                <div class="qq-dialog-message-selector"></div>
                <div class="qq-dialog-buttons">
                    <button class="qq-cancel-button-selector">No</button>
                    <button class="qq-ok-button-selector">Yes</button>
                </div>
            </dialog>

            <dialog class="qq-prompt-dialog-selector">
                <div class="qq-dialog-message-selector"></div>
                <input type="text">
                <div class="qq-dialog-buttons">
                    <button class="qq-cancel-button-selector">Cancel</button>
                    <button class="qq-ok-button-selector">Ok</button>
                </div>
            </dialog>
        </div>
        
    </script>
    
    <script>
        var uploader = new qq.FineUploader(
        {
            debug: true,

            element: document.getElementById('fine-uploader'),

            request: {
                endpoint: 'ImageUploader.ashx'
            },

            deleteFile: {
                enabled: true,
                endpoint: 'ImageUploader.ashx'
            },
            retry: {
                enableAuto: true
            },

            session: {
                refreshOnRequest: true
            },

            callbacks: {
                onError: function (id, name, errorReason, xhrOrXdr) {
                    alert(qq.format("Error on file number {} - {}.  Reason: {}", id, name, errorReason));
                },

                onDelete: function (id) {
                    this.setDeleteFileParams({ filename: this.getName(id) }, id);
                }
            }

        });
    </script>        
                  
                  </ContentTemplate>
     </asp:UpdatePanel>          
            </li>
           
            </ul>

           </div>

    </div>
</asp:Content>


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;

namespace BazaarOfCards.Members
{
    public partial class CreateListing : System.Web.UI.Page
    {
        /// <summary>
        /// Keeps the number of ListBox controls we dynamically add 
        /// to the page at runtime.
        /// </summary>
        private Int32 controlCount = 0;


        public List<ImageButton> m_Images = new List<ImageButton>();

        /// <summary>
        /// 
        /// </summary>
        //public string m_Step = "1";
        public string m_CatID = string.Empty;
        public string m_CategoryName = string.Empty;

        /// <summary>
        /// The panel object from the page
        /// </summary>
        Panel m_PanelListBoxControls;


        // Needed to get the panel from the content
        private Panel PanelListBox
        {
            get
            {
                if (m_PanelListBoxControls == null && Master != null)
                {
                    m_PanelListBoxControls = pnlContainer;
                }
                return m_PanelListBoxControls;
            }
        }

        protected void Page_Error(object sender, EventArgs e)
        {
            var ServerError = Server.GetLastError() as HttpException;

            if (ServerError != null)
            {
                int ErrorCode = ServerError.GetHttpCode();

                switch (ErrorCode)
                {
                    case 404:
                        Server.ClearError();
                        Server.Transfer("/ErrorPages/404.aspx");
                        break;
                    default:
                        Server.ClearError();
                        break;
                }
            }
        }


        /// <summary>
        /// 
        /// </summary>
        protected void Page_PreInit(Object sender, EventArgs e)
        {
            //EnsureChildControls();

            if (IsPostBack)
            {
                // m_Step = Request["Step"];

                // Re-create controls but not from datasource
                // The controlCount value is output in the page as a hidden field during PreRender.
                controlCount = Int32.Parse(Request.Form["controlCount"]); // assigns control count from persistence medium (hidden field)         

                for (Int32 i = 0; i < controlCount; i++)
                {
                    CreateDynamicListBoxGroup(false);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        protected void Page_Load(Object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Directory.Exists(HttpContext.Current.Server.MapPath("/Members/Uploads/" + HttpContext.Current.User.Identity.Name)))
                {
                    Directory.Delete(HttpContext.Current.Server.MapPath("/Members/Uploads/" + HttpContext.Current.User.Identity.Name), true);
                }

                //DataTable dt = null;
                //Dictionary<string, string> Params = new Dictionary<string, string>();
                //dt = Globals.g_DatabaseHandler.GetRecords(StoredProcedures.GetMainCategories, Params);

                CreateDynamicListBoxGroup(true);


                ListBox lb = (ListBox)pnlContainer.Controls[controlCount - 1];

                lb.Items.Add(new ListItem("One", "1"));
                 lb.Items.Add(new ListItem("Two", "2"));
                //lb.DataSource = dt;
                //lb.DataValueField = "ID";
                //lb.DataTextField = "Name";
                lb.DataBind();
            }
            //}
            //else
            //{
            //    throw new HttpException(404, "Page Not Found - " + Request.ServerVariables["URL"] + "?" + Request.QueryString);
            //}

        }

        /// <summary>
        /// 
        /// </summary>
        protected void Page_PreRender(Object sender, EventArgs e)
        {
            // persist control count
            ClientScript.RegisterHiddenField("controlCount", controlCount.ToString());
        }

        /// <summary>
        /// 
        /// </summary>
        private void ListBox_SelectedIndexChanged(Object sender, EventArgs e)
        {
            // First lets see if we need to remove any controls based on the index 
            // of the control the user clicked a item in.
            int index = pnlContainer.Controls.IndexOf((ListBox)sender);
            for (int i = pnlContainer.Controls.Count - 1; i > index; i--)
            {
                //PanelListBox.Controls[i].Visible = false;
                pnlContainer.Controls.RemoveAt(i);
                controlCount--;
            }

            ListBox lb = sender as ListBox;

            //Dictionary<string, string> Params = new Dictionary<string, string>();
            //Params.Add("ParentID", lb.SelectedValue);
            //DataTable Categories = Globals.g_DatabaseHandler.GetRecords(StoredProcedures.GetChildCategories, Params);

            //if (Categories.Rows.Count > 0)
            //{
            //    //btnStep1.Enabled = false;
            //    ImageSelected.Visible = false;
            //    CreateDynamicListBoxGroup(true);

            //    ListBox newLb = (ListBox)pnlContainer.Controls[controlCount - 1];

            //    newLb.DataSource = Categories; // use the same table
            //    newLb.DataValueField = "ID";
            //    newLb.DataTextField = "Name";
            //    newLb.DataBind();
            //}
            //else
            //{
                //btnStep1.Enabled = true;
                ImageSelected.Visible = true;
                GetCategoryBreadCrumb();
            //}

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="incrementCounter">
        /// If we are adding a new ListBox, this value will be true; otherwises 
        /// we are just redrawing all controls after postback
        /// </param>
        private void CreateDynamicListBoxGroup(Boolean incrementCounter)
        {
            ListBox lb = new ListBox();
            lb.AutoPostBack = true;
            lb.CssClass = "panel";
            lb.Width = 175;
            lb.Height = 150;

            // wire event delegate
            lb.SelectedIndexChanged += new EventHandler(ListBox_SelectedIndexChanged);

            PanelListBox.Controls.Add(lb);

            if (incrementCounter)
            {
                controlCount += 1;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnStep1_Click(object sender, EventArgs e)
        {
            //m_Step = "2";

            // Get the Category ID the listing is going to go.
            m_CatID = ((ListBox)pnlContainer.Controls[controlCount - 1]).SelectedValue;
            GetCategoryBreadCrumb();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnPrevious_Click(object sender, EventArgs e)
        {
            //m_Step = "1";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnFinish_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        protected void GetCategoryBreadCrumb()
        {
            for (int i = 0; i < pnlContainer.Controls.Count; i++)
            {
                if (i == pnlContainer.Controls.Count - 1)
                {
                    m_CategoryName += ((ListBox)pnlContainer.Controls[i]).SelectedItem.Text;
                }
                else
                {
                    m_CategoryName += ((ListBox)pnlContainer.Controls[i]).SelectedItem.Text + " > ";
                }
            }

            m_CatID = ((ListBox)pnlContainer.Controls[controlCount - 1]).SelectedValue;
        }
    }
}

Generalvery easy to understand...masterpiece..:-) Pin
Mohan_J18-Sep-15 19:31
Mohan_J18-Sep-15 19:31 
Questioncan we use gridview on the update panel Pin
makeitsimple23-Sep-13 21:26
professionalmakeitsimple23-Sep-13 21:26 
GeneralMy vote of 5 Pin
makeitsimple23-Sep-13 21:23
professionalmakeitsimple23-Sep-13 21:23 
QuestionThanks Pin
sridhargiri23-Sep-13 1:13
professionalsridhargiri23-Sep-13 1:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.