Recently, we were working on a project that required us to make an AJAX postback with a table cell (TD) onclick event. We were "forced" to do this because the webpage designer wanted the search results displayed in a table and the TD's had onmouseover, onmouseout and onmouseclick events. The way he designed it was very nice and we didn't want to change it because AJAX for .NET didn't natively support the TD click event.
We quickly searched the web for an answer and couldn't find anything. Over the past few months many others asked how to do it too, but nobody could provide an answer. It's really not that difficult...you just need to be a little creative and think how AJAX works in ASP.NET.
1<asp:Repeater ID="rptSearchResults" runat="server">
3 <table width="100%" border="0" cellpadding="0" cellspacing="4">
6 <td class="agentbox" onmouseover="style.backgroundColor='#e0e8f3';"
7 onclick="makeAJAXPostback('<%# DataBinder.Eval(Container.DataItem, "ID")%>')">
8 <%# DataBinder.Eval(Container.DataItem, "DisplayName")%>
9 <br />
10 <%# DataBinder.Eval(Container.DataItem, "Address1")%>
11 <br />
12 <%# DataBinder.Eval(Container.DataItem, "City")%>
13 <br />
14 <%# DataBinder.Eval(Container.DataItem, "StateIDCode")%>
15 <%# DataBinder.Eval(Container.DataItem, "Zip")%>
16 <br />
17 <%# DataBinder.Eval(Container.DataItem, "Phone")%>
At the bottom of the page, we added a the "makeAJAXPostback" function.
We also added a hidden field and a hidden HTML submit button:
1 <input type="submit" id="btnTDClicked" name="btnTDClicked" style="display: none" />
2 <input type="hidden" id="hidTDClickID" name="hidTDClickID" />
6 function makeAJAXPostback(TDClickID)
8 document.forms.hidTDClickID.value = TDClickID;
When the TD cell is clicked, the "makeAJAXPostback" function is called, the ID is put in the hidden field and the hidden button is clicked. Because the AJAX Toolkit handles all form postbacks, the button click is automatically made via AJAX.
All that's left is to handle the postback on the server. In Page_Load, we simply check if the hidden field is populated and process accordingly:
1//Handle TD Clicked Event when user clicks search results2if (Request.Form["hidTDClickID"] != null &&
3 Request.Form["hidTDClickID"].ToString() != "")
Hi, wondering if you could advise me on this, looks like what I need.
Awesome approach.. Saved me a bunch of time.. so obvious, but did not strike me.. glad you helped
Helped me to complete my task, thanks. Initially I was getting a full page postback because I had the hidden controls outside the Update Panel.
SICK. I'm thinking codebehind generated controls w/ this.
This seems to be greate
I am digging this stuff. I am writing a function that will post me back, to 1979.
Leave a Comment