Home > AJAX, Asp.net > Trigger partial postback from javascript

Trigger partial postback from javascript

Sometimes you would like to use javascript to trigger partial postback instead using a button click event.Here is how you do it. You can use the __doPostBack(case sensitive) to trigger a postback , if the target is an update panel ,the asp.net will intercept the request and trigger an partial postback instead.The Gotcha here is that you need to use UpdatePanel’s ClientId(which is automatically generated) rather than the UpdatePanel server side ID.
You put the following code in the markup.What you normally do is you put a button with
click event.And add a trigger in the update panel with Button ID.What I do here is that
I add a OnLoad event to the update panel and I use div’s onclick event to trigger a partial update.
You can change the javascript onclick event to any valid javascript
event to invoke the partial postback.

<asp:scriptmanager ID="myScriptManager" runat="server"></asp:scriptmanager>
 <div id="Container" onclick="__doPostBack('<% = myUpdatePanel.ClientID %>', '');">
 Click</div>
 <asp:UpdatePanel runat="server" ID="myUpdatePanel" OnLoad="myUpdatePanel_Load">
 <ContentTemplate>
 <asp:Literal runat="server" ID="myLiteral"></asp:Literal>
 <asp:Literal runat="server" ID="timeLiteral"></asp:Literal>
 </ContentTemplate>
 </asp:UpdatePanel>
You put the following code in the code behind.
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { myLiteral.Text = "First Request"; timeLiteral.Text = DateTime.Now.ToString(); } } protected void myUpdatePanel_Load(object sender, EventArgs e) { if (IsPostBack) { myLiteral.Text = "Partial Post back"; timeLiteral.Text = DateTime.Now.ToString(); } }

You can download the code sample from here.

Advertisements
Categories: AJAX, Asp.net
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: