ASP.NET AJAX UpdatePanel & Dynamic HTML Insertion Issue (Telerik) - c#

Ok so I have a problem. I am currently working on a project using the Telerik framework for ASP.NET AJAX, although that shouldnt matter much as I am bypassing Telerik completely (almost) for this portion of the work.
I'm putting together a facebook-like chat program into our company's CRM system and, while all has gone well up to this point, I've hit a roadblock. The problem is when I try to "create a new chatbox". I'm using the asp control UpdatePanel in conjunction with a jQuery $.ajax call to pass a JSON method name to my code behind file. Here's the JSON logic:
DoubleClick on user in userlist:
$telerik.$(".UserListEntry").dblclick(function () {
var ToName = $telerik.$(this).children(".UserListEntryName").text();
var FromName = $telerik.$("#lkUserGeneralSettings").text();
$telerik.$.ajax({
type: 'POST',
url: 'DefaultHandler.ashx',
data: { "ToName": ToName, "FromName": FromName },
success: CreateChatBox(),
error: function (response) { alert("error: 001"); }
});
});
CreateChatBox callback:
function CreateChatBox() {
$telerik.$.ajax({
type: 'POST',
url: 'Default.aspx',
data: { MethodName: "CreateChatBox" },
success: ForceAsyncPostback,
error: function (response) { alert("error: 002"); }
});
}
Force asyncpostback (shouldn't be necessary, but this doesnt even work either!):
function ForceAsyncPostback() {
var UpdatePanel1 = '<%=Panel3.ClientID%>';
if (UpdatePanel1 != null) {
__doPostBack(UpdatePanel1, '');
}
alert("Success");
}
The UpdatePanel is created through various literals and some hard-coded html good-ole' fashioned divs. The problem is NOT with the dynamic creation of said elements, this works just fine. In fact my code behind (which I will post below) creates and displays everything perfectly fine if I place it into my PageLoad event.
At any rate, here's the .aspx:
<asp:UpdatePanel ID="Panel3" runat="server" OnLoad="Panel3_Load" UpdateMode="Conditional">
<ContentTemplate>
<asp:Literal ID="ChatBoxesLiteralTop" runat="server" />
<asp:Literal ID="ChatBoxesLiteralMid" runat="server" />
<asp:PlaceHolder ID="ChatBoxesPlaceHolder" runat="server" />
<asp:Literal ID="ChatBoxesLiteralBot" runat="server" />
<div id="UserListCorner">
<img id="UserListBtn" src="images/list.png" />
</div>
<div id="UserList" class="UserListHidden">
<div id="UserListView">
<asp:Literal ID="UserListViewLiteral" runat="server" />
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind:
protected void Panel3_Load(object sender, EventArgs e)
{
#region Ajax methods
if (Request.Form["MethodName"] == "CreateChatBox")
{
CreateChatBox();
}
#endregion
Engine m_engine = new Engine();
string m_sql = #"SELECT FullName FROM Users WHERE RecordDeleted <> 1";
DataTable dt = m_engine.GetObjectsAsDataTable(m_sql);
for (int i = 0; i < dt.Rows.Count; i++)
{
UserListViewLiteral.Text += "<div class='UserListEntry'><span class='UserListEntryStatus'><img src='images/status-online.png' width='10' /></span> <span class='UserListEntryName'>" + dt.Rows[i]["FullName"].ToString() + "</span></div>";
}
RadAjaxManager.GetCurrent(Page).ResponseScripts.Add("ChatAjax()");
}
private void CreateChatBox()
{
ChatBoxesLiteralTop.Text = #"<div id='ChatBox' class='ChatBoxHidden'>
<div class='ChatBoxHeader'>
<img id='ChatBoxStatusBtn' src='Images/status-online.png' />
<span id='ChatBoxUserLabel'>John Doe</span>
<img id='closeBtn' src='Images/close.png' />
<img id='toggleTab' src='Images/up-arrow.png' />
</div>
<div id='ChatBoxMessageOutput'></div><div class='ChatBoxFooter'>";
TextBox txt = new TextBox();
txt.ID = "ChatBoxMessageInput";
txt.Height = 16;
txt.MaxLength = 270;
txt.Width = 250;
txt.AutoPostBack = false;
ChatBoxesPlaceHolder.Controls.Add(txt);
RadButton btn = new RadButton();
btn.ID = "ChatBoxSendButton";
btn.Text = "Send";
btn.AutoPostBack = true;
btn.Height = 22;
btn.Click += ChatBoxSendButton_Click;
ChatBoxesPlaceHolder.Controls.Add(btn);
ChatBoxesLiteralBot.Text = "</div></div>";
Panel3.Update();
RadAjaxManager.GetCurrent(Page).ResponseScripts.Add("ChatAjax()");
}
I'm certainly overlooking something outrageously stupid, but a fresh set of eyes from a seasoned ASP.Net Ajaxer would be really appreciated! Thanks in advance.
Clarification of Issue
What DOES work:
The code runs properly.
The JSON method is passed to the code behind and read.
The CreateChatBox() method runs through and allegedly populates the literals and controls.
All callbacks in the JSON chain are executed successfully.
What DOES NOT work:
The UpdatePanel, even after the redundant postback, does not have
this new HTML after code executes successfully.

To Whom It May Concern
Well I happened to solve this problem the day after posting it. Of course there are now new hurdles to tackle but I am happy to say that my asynchronous chat module is nearly done. Since nobody decided to take on the problem, I am going to post what I did to properly produce dynamic, asynchronous objects based on hard-coded HTML in ASP.NET since, while Googling the matter, this post was the only relevant result popping up.
I'll start by saying I am well aware that this is a very unconventional approach. That being said, the requirements of the project justified the means. While there may be many other ways to accomplish your goal, this does work. I am not going to go into extraneous details with respect to my particular project, but hopefully this will help somebody in the future.
The Wrongs
The primary problem with my original question was the way I was attacking the rendering sequence. A major flaw in my logic was attempting to separate the ASP controls (literals, placeholders, buttons and such) from my HTML too much. My initial approach (from above) looked like this:
<asp:UpdatePanel ID="Panel3" runat="server" OnLoad="Panel3_Load" UpdateMode="Conditional">
<ContentTemplate>
<asp:Literal ID="ChatBoxesLiteralTop" runat="server" />
<asp:Literal ID="ChatBoxesLiteralMid" runat="server" />
<asp:PlaceHolder ID="ChatBoxesPlaceHolder" runat="server" />
<asp:Literal ID="ChatBoxesLiteralBot" runat="server" />
<div id="UserListCorner">
<img id="UserListBtn" src="images/list.png" />
</div>
<div id="UserList" class="UserListHidden">
<div id="UserListView">
<asp:Literal ID="UserListViewLiteral" runat="server" />
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
The final result looks more like this:
<asp:UpdatePanel ID="Panel3" runat="server" OnLoad="Panel3_Load" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder ID="ChatBoxesPlaceHolder" runat="server" />
<div id="UserListCorner">
<img id="UserListBtn" src="images/list.png" />
</div>
<div id="UserList" class="UserListHidden">
<div id="UserListView">
<asp:Literal ID="UserListViewLiteral" runat="server" />
</div>
</div>
<asp:Label ID="Label42" Font-Bold="true" runat="server" />
<asp:HiddenField runat="server" ID="LatestDisplayTick" />
</ContentTemplate>
</asp:UpdatePanel>
With the code behind (abridged) similar to this:
Literal top = new Literal();
// ...
UpdatePanel UpdatePanel2 = new UpdatePanel();
// ...
top.Text = #"<div id='ChatBox' class='ChatBoxShown'>
<div class='ChatBoxHeader'>
<img id='ChatBoxStatusBtn' src='Images/status-online.png' />
<span id='ChatBoxUserLabel'>" + UserNames[0] + #"</span>
<img id='closeBtn' src='Images/close.png' />
<img id='toggleTab' src='Images/up-arrow.png' />
</div>";
top.ID = "ChatBoxesLiteralTop";
top.Mode = LiteralMode.PassThrough;
// ...
UpdatePanel2.ID = "UpdatePanel2";
UpdatePanel2.UpdateMode = UpdatePanelUpdateMode.Conditional;
UpdatePanel2.ChildrenAsTriggers = false;
UpdatePanel2.ContentTemplateContainer.Controls.Add(top2);
// ...
Panel3.ContentTemplateContainer.Controls.Add(top);
Panel3.ContentTemplateContainer.Controls.Add(UpdatePanel2);
Panel3.ContentTemplateContainer.Controls.Add(mid);
What It Means
All I've done is wrapped the entirety of my chatbox elements inside a single placeholder, dynamically creating HTML elements that wrap ASP controls all from the server and posting it as a "chunk" of dynamic data. This sidesteps some strange behaviors with ASP control placement otherwise, and allows for a quasi-OO approach for the client-side functionality of my project. After creation, I can now make use of some JSON and AJAX calls to dynamically enter data into said dynamically created controls.
An example would be posting a message received from a database notification to my chat window (ChatBoxesLiteralMid control) when it is received.
After Page/Control Load
if(ChatBoxesLiteralMid != null)
ChatBoxesLiteralMid.Text += #"<div class='ChatBoxEntry'><span class='ChatBoxEntryName ChatBoxSelf'>" + AppParameters.Current.AppUser.FirstName + "</span>: <span class='ChatBoxEntryMessage'>" + dy.Rows[dy.Rows.Count - 1]["Message"].ToString() + "</span></div>";
Why Go To The Trouble?
What I have accomplished is for a particular project with needs to go far above and beyond the original scope, started by another developer years prior. This is an unconventional way to teach the old dog some new tricks. I now have near-full control of an indiscriminate amount of real-time chat boxes/sessions on the CLIENT side. It's really pretty freakin' sweet honestly. Please feel free to post questions (or concerns) as I regularly check SO and am happy to respond.

Related

Clear Specific Textboxes ASPX page

I'm having trouble trying to clear these banking and routing numbers that are in a textbox on an aspx page. I've seen it used where they would just specify the ID of the textbox and do a textbox.text = String.Empty(). But that doesn't seem to work here. Maybe I'm using the wrong ID?? I also tried using JQuery .val("") but that didn't seem to work either.
Here's the code, i'd like to clear both Routing and Account text fields on click of a button:
<div id="DivUser1BankInfo" class="labelAndTextboxContainer">
<div class="labelContainer">
<asp:Label CssClass="rightFloat" ID="User1LabelRoutingNumber" runat="server" Text="Routing #:"></asp:Label><br />
</div>
<div class="textboxContainer">
<asp:TextBox ID="User1TextRoutingNumber" CssClass="leftFloat " runat="server" Font-Size="Smaller" Width="180px"
Text='<%# Bind("User1BankRoutingNumber") %>'
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' /><br />
</div>
<div class="labelContainer">
<asp:Label CssClass="rightFloat" ID="User1LabelAccountNumber" runat="server" Text="Account #:"></asp:Label><br />
</div>
<div class="textboxContainer">
<asp:TextBox ID="User1TextAccountNumber" CssClass="leftFloat " runat="server" Font-Size="Smaller" Width="180px"
Text='<%# Bind("User1BankAccountNumber") %>'
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' /><br />
</div>
<button type="button" id="clearButton1">Clear</button>
<div class="button">
<asp:Button ID="User1ClearBankInfo" runat="server" Text="Reset"
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' OnClick="clearFields_btn"/><br />
</div>
The OnClick= "clearFields_btn" code behind =
protected void clearFields_btn(object sender, EventArgs e)
{
}
Thanks for any help!
I haven't worked with ASP.NET in a little while, but I think you may want the OnClientClick event, not OnClick. OnClientClick is for client-side code (your jQuery/JavaScript) and OnClick is for server-side code (your C# or VB.NET).
You'd also want your OnClientClick event method to return false, or the server-side code will also fire.
So I think you want something like:
<asp:Button ID="User1ClearBankInfo" runat="server" Text="Reset"
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>
OnClientClick="clearText();"/>
And then clearText would look like this:
<script>
function clearText()
{
//our two IDs
$('input[id*="User1TextRoutingNumber"]').each(function(index) {
$(this).val('');
});
$('input[id*="User1TextAccountNumber"]').each(function(index) {
$(this).val('');
});
return false;
}
</script>
EDIT: shoot, I see my mistake. Fixed the code to clear the text of the textbox, not the button ("this").
Edit: removed the space from the "clear" text val.
EDIT: Made search a little more flexible, less dependent on GridView or no GridView.
Try this
<script>
var clear = function(textboxID){$('input[id*=' + textboxID + ']').val('');};
return false;
</script>
<button id="btClearText" onclick="javascript:return clear('txtName');">
but if you need a more specific answer then please post more information
You need something like this. Assuming you want a client side solution (not very clear from your question).
<script type="text/javascript">
function clearTextBox() {
document.getElementById("<%= User1TextRoutingNumber.ClientID %>").value = "";
//or
$("#<%= User1TextRoutingNumber.ClientID %>").val("");
}
</script>
The <%= User1TextRoutingNumber.ClientID %> will ensure you get the correct ID for javascript/jQuery.
A server side solution would be:
protected void clearFields_btn(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
TextBox tb = GridView1.Rows[i].FindControl("User1TextAccountNumber") as TextBox;
tb.Text = "";
}
}

_doPostBack not definted in JavaScript

here is my ASP web Control
<a id="geoLocation" class="geolocate box-outline active full">
<div>
<div class="icon"></div>
<div class="header">
Locate Me Now
<asp:Label id="latitude" runat="server" ClientIdMode="Static"></asp:Label><br />
<asp:Label id="longitude" runat="server" ClientIdMode="Static"></asp:Label>
<div style="display:none">
<asp:Button ID="Button2" runat="server" Text="Button" ClientIdMode="Static" />
</div>
</div>
</div>
</a>
I am trying to do a Postback to be able to access the values of "longitude" and "latitude", in the code behind which I intend to make hidden.
this is the postback in Javascipt that I am using ... what am I doing wrong?
function showPosition(position) {
// x.innerHTML = "Latitude: " + position.coords.latitude +
// "<br>Longitude: " + position.coords.longitude;
document.getElementById('latitude').innerHTML = position.coords.latitude;
document.getElementById('longitude').innerHTML = position.coords.longitude;
_doPostBack('#geoLocation', '');
}
First, make sure you have two underscores at the beginning of __doPostBack.
Second, the __doPostBack function is only available if at least one control on the page calls Page.RegisterPostBackScript(). Unfortunately, this method is internal to System.Web.
As a workaround, your control can override Render and call GetPostBackEventReference, which will call Page.RegisterPostBackScript() for you and return a bit of JavaScript that can be ignored:
protected override void Render(HtmlTextWriter writer)
{
this.Page.ClientScript.GetPostBackEventReference(new PostBackOptions(this));
base.Render(writer);
}
Third (in answer to a question you haven't asked yet), setting the innerHTML property of a Label control will not make the value available to the server on postback. You should instead use a HiddenField control and set its value property in JavaScript.
Try this:
_doPostBack('#geoLocation', ''); --> __doPostBack('#geoLocation', '');
You need two underscores at the beginning of the doPostBack method.

doPostBack from C# with JavaScript

hi I have one parent page which opens a pop up window, and user makes some changes on child pop up page then clicks a save button.
When the user clicks the save button, I want to doPostBack to the parent page so that the changes made in the pop up window can be seen in parent window.
Question : How can I achive the above scenario?
I want to write the script code in aspx.cs file, I tried
string script = "";
script = "<script>window.opener.__doPostBack('UpdatePanel1', '')</script>";
ScriptManager.RegisterClientScriptBlock(Literal1, typeof(Literal), "yenile", script, true);
but this did not do anything, no errors just nothing.
I am new to JavaScript, need help with all steps.
The parent page:
<asp:UpdatePanel runat="server">
<ContentTemplate>
<div>
<asp:Literal runat="server" ID="ChildWindowResult" />
</div>
<hr />
<input type="button" value="Open Dialog" onclick="window.open('MyDialog.aspx', 'Dialog');" />
<asp:Button ID="HiddenButtonForChildPostback" runat="server"
OnClick="OnChildPostbackOccured" style="display: none;" />
<asp:HiddenField runat="server" ID="PopupWindowResult"/>
</ContentTemplate>
</asp:UpdatePanel>
The MyDialog page:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
function postData() {
var resultField = $("input[type='hidden'][id$='PopupWindowResult']", window.opener.document);
var parentPosDataButton = $("[id$='HiddenButtonForChildPostback']", window.opener.document);
resultField.val($("#<%= SomeValueHiddenField.ClientID %>").val());
parentPosDataButton.click();
}
</script>
<asp:TextBox runat="server" ID="SomeValueHiddenField" />
<asp:Button runat="server" OnClick="PostData" Text="Click Me" />
protected void PostData(object sender, EventArgs e)
{
SomeValueHiddenField.Value = DateTime.Now.ToString();
ClientScript.RegisterStartupScript(this.GetType(), "PostData", "postData();", true);
}
But I believe that it would be much better to utilize here some pop-up controls like PopUpExtender from the AjaxControlToolkit library or dialog from the jQuery-UI.
You probably need to use ClientID:
string script = "";
script = "<script>window.opener.__doPostBack('" + UpdatePanel1.ClientID + "', '')</script>";
ScriptManager.RegisterClientScriptBlock(Literal1, typeof(Literal), "yenile", script, true);
The last parameter is to whether include script tag or not
So, if you do
RegisterClientScriptBlock(page,type, "<script>foo();</script>", true);
You will end up with:
"<script><script>foo();</script></script>"
So, change your last parameter to false, or better yet, remove the tags in the string
Review the following suggested solution:
http://livshitz.wordpress.com/2011/06/12/use-popup-to-postbackupdate-its-parentopener-without-losing-viewstate-values-and-close/#more-16

Setting hidden input value in Javascript, then accessing it in codebehind

I have been trying to set the value of a hidden input by using Javascript and then access the value from within my C# codebehind. When I run the code that is copied below, the value that is assigned to assignedIDs is "", which I assume is the default value for a hidden input. If I manually set the value in the html tag, then assignedIDs is set to that value.
This behavior suggests to me that the value of the input is being reset (re-rendered?) between the onClientClick and onClick events firing.
I would appreciate any help with the matter. I have spent hours trying to solve what seems like a very simple problem.
html/javascript:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Admin Page - Manage Tasks</title>
<script language="javascript" type="text/javascript">
function PopulateAssignedIDHiddenInput() {
var source = document.getElementById('assignedLinguistListBox');
var s = "";
var count = source.length;
for (var i = count - 1; i >= 0; i--) {
var item = source.options[i];
if (s == "") { s = source.options[i].value; }
else { s = s.concat(",",source.options[i].value); }
}
document.getElementById('assignedIDHiddenInput').Value = s;
// I have confirmed that, at this point, the value of
// the hidden input is set properly
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel id="EditMode" runat="server">
<table style="border: none;">
<tr>
<td>
<asp:Label ID="availableLinguistLabel" runat="server" Text="Available"></asp:Label><br />
<asp:ListBox ID="availableLinguistListBox" runat="server" Rows="10" SelectionMode="Multiple"></asp:ListBox>
</td>
<td>
<input type="button" name="right" value=">>"
onclick="Javascript:MoveItem('availableLinguistListBox', 'assignedLinguistListBox');" /><br /><br />
<input type="button" name="left" value="<<"
onclick="Javascript:MoveItem('assignedLinguistListBox', 'availableLinguistListBox');" />
</td>
<td>
<asp:Label ID="assignedLinguistLabel" runat="server" Text="Assigned To"></asp:Label><br />
<asp:ListBox ID="assignedLinguistListBox" runat="server" Rows="10" SelectionMode="Multiple"></asp:ListBox>
</td>
</tr>
</table>
//-snip-
<asp:Button ID="save_task_changes_button" runat="server" ToolTip="Click to save changes to task"
Text="Save Changes" OnClick="save_task_changes_button_click" OnClientClick="Javascript:PopulateAssignedIDHiddenInput()" />
</asp:Panel>
<!-- Hidden Inputs -->
<!-- Note that I have also tried setting runat="server" with no change -->
<input id="assignedIDHiddenInput" name="assignedIDHiddenInput" type="hidden" />
</div>
</form>
</body>
c#
protected void save_task_changes_button_click(object sender, EventArgs e)
{
string assignedIDs = Request.Form["assignedIDHiddenInput"];
// Here, assignedIDs == ""; also, Request.Params["assignedIDHiddenInput"] == ""
// -snip-
}
In javascript you need the value property to be lowercase, like this:
document.getElementById('assignedIDHiddenInput').value = s;
Then it will be set properly :) You can see an example in action here
Though if you alert the .Value it will show your value, you've actually added a new .Value property, but you haven't set the input's .value property which is what gets posted to the server. The example link above illustrates this both ways.
Also you can make it a bit faster especially if you have lots of options by using an array instead of string concatenation, like this:
var source = document.getElementById('assignedLinguistListBox');
var opts = [];
for (var i = 0; i < source.options.length; i++) {
opts.push(source.options[i].value);
}
var s = opts.join(',');
Edit: The above code is updated, CMS is right that the previous method was browser dependent, the above should now behave consistently. Also, if jQuery is an option, there are shorter ways of getting this info still, like this:
var s = $('#assignedLinguistListBox option').map(function() {
return this.value;
}).get().join(',');
$('#assignedIDHiddenInput').val(s);
You can see a working example of this here
I'm assuming ASP.NET here.
If so, your problem is the id of the control in the HTML generated by ASP.NET is not going to be "assignedIDHiddenInput" that you reference in the script. ASP.NET changes those before rendering the HTML from what you specify in the HTML page declaratively. Do a view source on the page and you will see what I mean.
Here is a way around that:
document.getElementById('<%=assignedIDHiddenInput.ClientID %>').value = s;
Update: As noted in the comments, this is only relevant if the control is set to RunAt=Server.
I think ASP.NET is calling the javascript to execute a postback on that control before your javascript function is called to populate that hidden value.
I think it's possible to disable the default postback and handle it yourself but I'm sure others can advise better.
Stick an alert() into your function there to see if it is really getting called before post-back is triggered.

ASP.NET HoverMenuExtender Lazy Loading

I'm trying to get my hovermenuextenders to do some lazy loading. I have avatars across the site that when hovered over should pull back various things (images, recent posts, post count, etc) For obvious reasons I don't want to do this for all avatars on the page_load.
Using the following code I'm able to get the hover event to trigger a postback to the server asynchronously (breakpoint is hit onmouseover). However, the commands in the postback don't seem to be reflected after execution is done. The loading image/label stay in the hover panel. Any help is appreciated!
EDIT: I just realized that the very last avatar rendered on the page works properly but none of the ones above it do. Any ideas what might be causing this strange behavior?
<script language="javascript" type="text/javascript">
function OnHover(image) {
__doPostBack('<%= this.imageHoverTrigger.UniqueID %>', '');
}
</script>
<!-- DUMMY Hover Trigger -->
<input id="imageHoverTrigger" runat="server" style="display:none;"
type="button" onserverclick="imageHoverTrigger_Click" />
<!-- User Avatar -->
<div style="border: solid 1px #AAA; padding:2px; background-color:#fff;">
<asp:ImageButton ID="UserImg" runat="server" />
</div>
<!-- Hover tooltip disabled by default
(Explicitly enabled if needed)-->
<ajax:HoverMenuExtender ID="UserInfoHoverMenu" Enabled="false" runat="server"
OffsetX="-1"
OffsetY="3"
TargetControlID="UserImg"
PopupControlID="UserInfoPanel" dyn
HoverCssClass="userInfoHover"
PopupPosition="Bottom">
</ajax:HoverMenuExtender>
<!-- User Profile Info -->
<asp:Panel ID="UserInfoHover" runat="server" CssClass="userInfoPopupMenu">
<asp:UpdatePanel ID="UserInfoUpdatePanel" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:Image ID="loadingImg" runat="server" ImageUrl="~/Design/images/ajax-loader-transp.gif" />
<asp:Label ID="loadingLbl" runat="server" Text="LOADING..." ></asp:Label>
<asp:Panel ID="UserInfo" runat="server" Visible="false">
<b><asp:Label ID="UserNameLbl" runat="server"></asp:Label><br /></b>
<span style="font-size:.8em">
<asp:Label ID="UserCityLbl" runat="server" Visible="false"></asp:Label> <asp:Label ID="UserStateLbl" runat="server" Visible="false"></asp:Label>
</span>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="imageHoverTrigger" />
</Triggers>
</asp:UpdatePanel>
</asp:Panel>
And the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
UserImg.Attributes.Add("onmouseover", "javascript:OnHover(this)");
}
protected void imageHoverTrigger_Click(object sender, EventArgs args)
{
// Hide loading image/label
loadingLbl.Visible = false;
loadingImg.Visible = false;
//TODO: Set user data here
UserInfo.Visible = true;
}
Figured it out:
My Page_Load event hookup should've been:
UserImg.Attributes.Add("onmouseover", "javascript:OnHover('" + this.imageHoverTrigger.UniqueID + "','" + this.hiddenLbl.ClientID + "')");
UserImg.Attributes.Add("onmouseout", "javascript:ClearTimer()");
and the javascript function should've been:
var hoverTimer;
// Called on the hover of the user image
function OnHover(trigger, hiddenTxt) {
var field = document.getElementById(hiddenTxt);
// Only post if this hover hasn't been done before
if (field == null || field.innerHTML == "false") {
hoverTimer = setTimeout(function() { ShowInfo(trigger) }, 500);
}
}
// Clears timeout onmouseout
function ClearTimer() {
clearTimeout(hoverTimer);
}
// Retrieves user info from server
function ShowInfo(trigger) {
__doPostBack(trigger, '');
}
I also added a hidden field on the form in order to know when the hover has been executed. The code behind sets the hidden field to true and my javascript checks for the value of the hidden field each time it executes. This stops the code from doing round trips each time the user hovers over the image.

Categories