Wednesday, March 28, 2012

Ajax Updateprogress bar

Hi

I am ussing Ajax controls, and I have a problem to implement a Update progress bar with a to different Update panel.

This is my problem I have a Two diferent Gridview in to different Updatepanel and one Updateprogress bar, the first Updatepanel with the first Gridview has to be updated automatically each 1 second with a timer control process, and and the other Updatepaanel and gridview has to be Updated when I press a button control and has to be appear the progress bar that I put in the Updateprogress bar but is not working as I am saying, when the page is Load the first Gridwiew start to Updated automatically and also the progress bar appear, and when I press the Button to update the other Gridview is also appear the progress bar and when is finish to Update the gridview the progress bar is continusly working.

any suggestion to solve this problem

Thanks and regards.

You can use separate UpdateProgress for each UpdatePanel. Set the AssociateUpdatePanelID of the UpdateProgress control to your designated UpdatePanel.

AJAX UpdateProgress

hi

i working with AJAX recently i am facing one problem in UpdateProgress control.It work fine display the message and animation picture perfect.My problem is i want pass a Value to updateprogress control in Example now it give me

Updating databases ..... and some animation.

i want

Updating Databases Employee Name : XXXXXXXXXXXXXXXXXXXX & animation.

How to pass these value in label control in updateprogress control ?

Q2) in UpdateProgress Run how to disable other control execpt the cancel button in updateprogress control ? Or a popup dialog box display on middle of page and disbaled the main web page unless u cancel the control ?

Q3) AJAX control work with microsoft product with out any problem.when i try with component art products it give me error Sys.event.Ui.Dom what could be reason.

Q3)

For Question 1, seehttp://forums.asp.net/t/1152621.aspx

Question 2, you can use a Modal Popup approach. Example here:http://www.visoftinc.com/samples/UpdateProgress.aspx and how to do this, here:http://blogs.visoftinc.com/archive/2007/09/10/modalupateprogress.aspx

Question 3, not to familar with Component Art; you may want to check over in their forums...

-Damien

Ajax UpdatePanels and datalists

I have 2 datalists:

datalist1 (inside UpdatePanel1 with UpdateMode as conditional)

datalist2 (outside UpdatePanel1)

On click of an ImageButton in datalist2, I am executing the datalist2_ItemCommand event handler & adding some data in the database. After which in the same code, I am calling the DataBind() on datalist1 and then calling Update() method on UpdatePanel.

My problem is because of the datalist2_ItemCommand event, a full postback occurs instead of just updating the datalist inside the UpdatePanel1. Is there a way I can just refresh the datalist1 instead of both the datalists getting refreshed?

I read about using Web Service on the net, but have a feeling that I can probably handle the database update in it, but will not be able to access the datalist1 to call its DataBind() event or UpdatePanel1 to call its Update() method in it.

I have already spent a day trying to figure how to make this work...could someone please guide me in the right direction?

Thanks

Hi

I think what is missing is to get Ajax to intecept the postback that is done by datalist2. This is done by adding and asyncpostback trigger for the updatepanel that handles the itemcommand event of datalist2. (how to add an asyncpostpacktrigger is explained herehttp://asp.net/ajax/documentation/live/tutorials/IntroductionUpdatePanel.aspx pretty fare down on the page)

TAG


See this

http://www.asp.net/ajax/documentation/live/tutorials/UsingUpdatePanelControls.aspx


You are right, adding a asyncpostback trigger would help here. However, I have a slightly different issue. Sorry for not mentioning correctly the first time, but I have my 2nd datalist (datalist2) also in a UpdatePanel (UpdatePanel2) & thats when it does not work. If I don't place it in an UpdatePanel, the solution you suggested works.

The reason I need to place the 2nd datalist in an UpdatePanel is because there is another imagebutton called "Delete" in it, which when clicked, deletes the corresponding image in that cell of the datalist2 & refreshes the datalist.

basically, the functionality desired is:

if the main thumbnail image is clicked in the datalist2, then it is added to the list of images displayed in datalist1 (displayed in UpdatePanel1) & if the "Delete" image is clicked, then that thumbnail is removed from datalist2 & so only UpdatePanel2 should be refreshed.

Thanks for you help...


also, the updatemode for UpdatePanel2 is also set to conditional:

Here's how the code looks like:

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DataList2" />
</Triggers>
<ContentTemplate>
<asp:DataList ID="DataList1" runat="server" DataSourceID="Ods1" BorderStyle="Solid" GridLines="Both" RepeatDirection="Horizontal">
<ItemTemplate>
<asp:ImageButton ID="ThumbImage1" runat="server" ImageUrl='<imagepath...>' />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
<ItemStyle Width="150px" />
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DataList ID="DataList2" runat="server" RepeatColumns="4" DataSourceID="Ods2" BorderStyle="Solid" GridLines="Both" RepeatDirection="Horizontal" OnItemCommand="DataList2_ItemCommand" CellPadding="5">
<ItemTemplate>
<asp:ImageButton ID="ThumbImage2" runat="server" ImageUrl='<imagepath...>' CommandName="ThumbImage" CommandArgument='<passing the id...>' />
<br />
<asp:ImageButton ID="DeleteImage" runat="server" ImageUrl="images/delete.gif" CommandName="DeleteImage" CommandArgument='<passing the id...>' />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
<ItemStyle Width="150px" />
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>

and the code in DataList2_ItemCommand is as follows:

protected void DataList2_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "DeleteImage")
{
//code to delete the image from database

...
this.DataList2.DataBind();
this.UpdatePanel2.Update();
}
else if (e.CommandName == "ThumbImage2")
{
//code to add the thumb image to the table attached to datalist1.
...
...
this.Datalist1.DataBind();
this.UpdatePanel1.Update();
}
}

hope this helps...


I think setting the property ChildrenAsTriggers = "false" for UpdatePanel2 solved the problem.

Thanks

AJAX UpdatePanel, ASP.NET Repeater Control, and custom JavaScript for postback - Single ro

Good afternoon, everyone.

I am running into an interesting problem with the AJAX UpdatePanel and the ASP.NET Repeater control. For some background, we have been asked to develop a dynamic single row update for a data table that needs to be maintained by the users. The analyst does not want to use buttons, as this is supposed to be a data entry style of application (hands on keyboard at all times, no mouse interaction). The following rules define the behavior the analyst wants to have happen:

When a user changes the data in a row, the row should be marked as changed but not saved yet. (No individual control saves to the database.)

When a user leaves a row that has been changed, that row should be posted back to the server and saved to the database.

I was able to get this partly working with a GridView inside of an UpdatePanel, by using some custom client-side JavaScript to detect changes and to determine when to call __doPostBack to force the save to the database.

However, the entire GridView is posting back each time, which is not the desired effect. The analyst wants each row to post back individually. We are also running into enough of a performance bottleneck with the GridView postback, that we decided to try using Repeater instead, with an UpdatePanel around each row of data.

Unfortunately, changing the GridView to a Repeater turned out to be problematic. I am running into the following issues:

When the custom __doPostBack JavaScript method is called by a control inside a Repeater, which is nested inside an UpdatePanel, the entire page is posting back instead of just the UpdatePanel.

When attempting to move the JavaScript from the .aspx page to a JavaScript .js file, the client-side JavaScript aborts with an "Object expected" error when the custom __doPostBack JavaScript method is called. (The same code works fine when embedded in the .aspx page.)

I have managed to prune down the code to the bare essentials, and I was able to replicate these problems with standard ASP.NET code.

Would some of you please look over the code below and let me know if there is something obvious that I am doing wrong? Or would someone please explain why this is working fine for GridView but not for Repeater?

Thanks in advance for any help that you can provide.

We also have a suggestion to convert the custom JavaScript to server-side code by building custom controls that would expose OnFocus as a server-side event. Have any of you done something like this before? If so, do those custom controls work with the AJAX UpdatePanel?

Jeff Parker
Senior Software Developer
Explore Information Services


default.aspx - UpdatePanel contains Repeater control, client-side JavaScript embedded in the aspx page

-- default.aspx

<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Untitled Page</title></head><body> This is some text sitting outside the main control. It should not be refreshed by AJAX.<%=DateTime.Now%><br /> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" /> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="conditional"> <ContentTemplate> <script type="text/javascript"> var currentRowChanged = -1; function SetRowChanged(rowIndex) { currentRowChanged = rowIndex; } function CheckRowChanged(repeaterUniqueID, controlID, newRowIndex) { if((currentRowChanged != -1) && (currentRowChanged != newRowIndex)) { saveInfo = 'SaveData$' + controlID + '$' + currentRowChanged + '$' + newRowIndex; currentRowChanged = -1; __doPostBack(repeaterUniqueID, saveInfo); } } </script> <asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound" > <HeaderTemplate> This is inside the update panel and should be updated.<%=DateTime.Now%><br /> </HeaderTemplate> <ItemTemplate> <asp:TextBox ID="TextBox1" runat="server" />  <asp:TextBox ID="TextBox2" runat="server" />  <asp:TextBox ID="TextBox3" runat="server" /><br /> </ItemTemplate> </asp:Repeater> </ContentTemplate> </asp:UpdatePanel> </form></body></html>

-- default.aspx.cs

using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partialclass _Default : System.Web.UI.Page {protected void Page_Load(object sender, EventArgs e) {if(!IsPostBack) { BindData(); }else {if (Request.Form["__EVENTTARGET"].Contains(Repeater1.UniqueID.Replace(':','$'))) {if (Request.Form["__EVENTARGUMENT"].Contains("SaveData$")) {string[] aszSaveParameters = Request.Form["__EVENTARGUMENT"].Split('$');string szCurrentControlID = aszSaveParameters[1];int iSaveItemIndex = Convert.ToInt32(aszSaveParameters[2]);int iCurrentRowIndex = Convert.ToInt32(aszSaveParameters[3]); RandomizeRow(iSaveItemIndex); ScriptManager1.SetFocus(szCurrentControlID); } } } }private void RandomizeRow(int index) { RepeaterItem riSaveRow = Repeater1.Items[index]; Random oRandom =new Random(); TextBox TextBox1 = (TextBox)riSaveRow.FindControl("TextBox1"); TextBox1.Text = Convert.ToString(oRandom.Next()); TextBox TextBox2 = (TextBox)riSaveRow.FindControl("TextBox2"); TextBox2.Text = Convert.ToString(oRandom.Next()); TextBox TextBox3 = (TextBox)riSaveRow.FindControl("TextBox3"); TextBox3.Text = Convert.ToString(oRandom.Next()); }private void BindData() { Repeater1.DataSource = GetSampleData(); Repeater1.DataBind(); }private DataTable GetSampleData() { DataTable dtbSampleData =new DataTable(); dtbSampleData.Columns.Add("TestColumn1",typeof(string)); dtbSampleData.Columns.Add("TestColumn2",typeof(string)); dtbSampleData.Columns.Add("TestColumn3",typeof(string)); DataRow drSampleData = dtbSampleData.NewRow(); drSampleData["TestColumn1"] ="column 1, row 1"; drSampleData["TestColumn2"] ="column 2, row 1"; drSampleData["TestColumn3"] ="column 3, row 1"; dtbSampleData.Rows.Add(drSampleData); drSampleData = dtbSampleData.NewRow(); drSampleData["TestColumn1"] ="column 1, row 2"; drSampleData["TestColumn2"] ="column 2, row 2"; drSampleData["TestColumn3"] ="column 3, row 2"; dtbSampleData.Rows.Add(drSampleData); drSampleData = dtbSampleData.NewRow(); drSampleData["TestColumn1"] ="column 1, row 3"; drSampleData["TestColumn2"] ="column 2, row 3"; drSampleData["TestColumn3"] ="column 3, row 3"; dtbSampleData.Rows.Add(drSampleData); drSampleData = dtbSampleData.NewRow(); drSampleData["TestColumn1"] ="column 1, row 4"; drSampleData["TestColumn2"] ="column 2, row 4"; drSampleData["TestColumn3"] ="column 3, row 4"; dtbSampleData.Rows.Add(drSampleData); drSampleData = dtbSampleData.NewRow(); drSampleData["TestColumn1"] ="column 1, row 5"; drSampleData["TestColumn2"] ="column 2, row 5"; drSampleData["TestColumn3"] ="column 3, row 5"; dtbSampleData.Rows.Add(drSampleData); dtbSampleData.AcceptChanges();return dtbSampleData; }protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e) {if((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem)) { DataRowView drvSampleData = (DataRowView) e.Item.DataItem; TextBox TextBox1 = (TextBox)e.Item.FindControl("TextBox1"); TextBox1.Text = Convert.ToString(drvSampleData["TestColumn1"]); TextBox1.Attributes["onchange"] ="javascript:SetRowChanged(" + e.Item.ItemIndex +")"; TextBox1.Attributes["onfocus"] ="javascript:CheckRowChanged('" + Repeater1.UniqueID +"', '" + TextBox1.ClientID +"', " + e.Item.ItemIndex +")"; TextBox TextBox2 = (TextBox)e.Item.FindControl("TextBox2"); TextBox2.Text = Convert.ToString(drvSampleData["TestColumn2"]); TextBox2.Attributes["onchange"] ="javascript:SetRowChanged(" + e.Item.ItemIndex +")"; TextBox2.Attributes["onfocus"] ="javascript:CheckRowChanged('" + Repeater1.UniqueID +"', '" + TextBox1.ClientID +"', " + e.Item.ItemIndex +")"; TextBox TextBox3 = (TextBox)e.Item.FindControl("TextBox3"); TextBox3.Text = Convert.ToString(drvSampleData["TestColumn3"]); TextBox3.Attributes["onchange"] ="javascript:SetRowChanged(" + e.Item.ItemIndex +")"; TextBox3.Attributes["onfocus"] ="javascript:CheckRowChanged('" + Repeater1.UniqueID +"', '" + TextBox1.ClientID +"', " + e.Item.ItemIndex +")"; } }protected override void RaisePostBackEvent(System.Web.UI.IPostBackEventHandler sourceControl,string eventArgument) {if ((eventArgument !=null) && (eventArgument.Contains("SaveData$"))) {// Do nothing }else {base.RaisePostBackEvent(sourceControl, eventArgument); } }}

default2.aspx - UpdatePanel contains Repeater control, client-side JavaScript included using ScriptManager.RegisterClientScriptInclude method

-- default2.aspx

<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="_Default2" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Untitled Page</title></head><body> This is some text sitting outside the main control. It should not be refreshed by AJAX.<%=DateTime.Now%><br /> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" /> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="conditional"> <ContentTemplate> <asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound" > <HeaderTemplate> This is inside the update panel and should be updated.<%=DateTime.Now%><br /> </HeaderTemplate> <ItemTemplate> <asp:TextBox ID="TextBox1" runat="server" />  <asp:TextBox ID="TextBox2" runat="server" />  <asp:TextBox ID="TextBox3" runat="server" /><br /> </ItemTemplate> </asp:Repeater> </ContentTemplate> </asp:UpdatePanel> </form></body></html>

-- default2.aspx.cs

using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partialclass _Default2 : System.Web.UI.Page {protected void Page_Load(object sender, EventArgs e) {if(!IsPostBack) {if (!ClientScript.IsClientScriptIncludeRegistered("SingleRowUpdate")) { ScriptManager.RegisterClientScriptInclude(this,typeof (Page),"SingleRowUpdate","JScript.js"); } BindData(); }else {if (Request.Form["__EVENTTARGET"].Contains(Repeater1.UniqueID.Replace(':','$'))) {if (Request.Form["__EVENTARGUMENT"].Contains("SaveData$")) {string[] aszSaveParameters = Request.Form["__EVENTARGUMENT"].Split('$');string szCurrentControlID = aszSaveParameters[1];int iSaveItemIndex = Convert.ToInt32(aszSaveParameters[2]);int iCurrentRowIndex = Convert.ToInt32(aszSaveParameters[3]); RandomizeRow(iSaveItemIndex); ScriptManager1.SetFocus(szCurrentControlID); } } } }private void RandomizeRow(int index) { RepeaterItem riSaveRow = Repeater1.Items[index]; Random oRandom =new Random(); TextBox TextBox1 = (TextBox)riSaveRow.FindControl("TextBox1"); TextBox1.Text = Convert.ToString(oRandom.Next()); TextBox TextBox2 = (TextBox)riSaveRow.FindControl("TextBox2"); TextBox2.Text = Convert.ToString(oRandom.Next()); TextBox TextBox3 = (TextBox)riSaveRow.FindControl("TextBox3"); TextBox3.Text = Convert.ToString(oRandom.Next()); }private void BindData() { Repeater1.DataSource = GetSampleData(); Repeater1.DataBind(); }private DataTable GetSampleData() { DataTable dtbSampleData =new DataTable(); dtbSampleData.Columns.Add("TestColumn1",typeof(string)); dtbSampleData.Columns.Add("TestColumn2",typeof(string)); dtbSampleData.Columns.Add("TestColumn3",typeof(string)); DataRow drSampleData = dtbSampleData.NewRow(); drSampleData["TestColumn1"] ="column 1, row 1"; drSampleData["TestColumn2"] ="column 2, row 1"; drSampleData["TestColumn3"] ="column 3, row 1"; dtbSampleData.Rows.Add(drSampleData); drSampleData = dtbSampleData.NewRow(); drSampleData["TestColumn1"] ="column 1, row 2"; drSampleData["TestColumn2"] ="column 2, row 2"; drSampleData["TestColumn3"] ="column 3, row 2"; dtbSampleData.Rows.Add(drSampleData); drSampleData = dtbSampleData.NewRow(); drSampleData["TestColumn1"] ="column 1, row 3"; drSampleData["TestColumn2"] ="column 2, row 3"; drSampleData["TestColumn3"] ="column 3, row 3"; dtbSampleData.Rows.Add(drSampleData); drSampleData = dtbSampleData.NewRow(); drSampleData["TestColumn1"] ="column 1, row 4"; drSampleData["TestColumn2"] ="column 2, row 4"; drSampleData["TestColumn3"] ="column 3, row 4"; dtbSampleData.Rows.Add(drSampleData); drSampleData = dtbSampleData.NewRow(); drSampleData["TestColumn1"] ="column 1, row 5"; drSampleData["TestColumn2"] ="column 2, row 5"; drSampleData["TestColumn3"] ="column 3, row 5"; dtbSampleData.Rows.Add(drSampleData); dtbSampleData.AcceptChanges();return dtbSampleData; }protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e) {if((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem)) { DataRowView drvSampleData = (DataRowView) e.Item.DataItem; TextBox TextBox1 = (TextBox)e.Item.FindControl("TextBox1"); TextBox1.Text = Convert.ToString(drvSampleData["TestColumn1"]); TextBox1.Attributes["onchange"] ="javascript:SetRowChanged(" + e.Item.ItemIndex +")"; TextBox1.Attributes["onfocus"] ="javascript:CheckRowChanged('" + Repeater1.UniqueID +"', '" + TextBox1.ClientID +"', " + e.Item.ItemIndex +")"; TextBox TextBox2 = (TextBox)e.Item.FindControl("TextBox2"); TextBox2.Text = Convert.ToString(drvSampleData["TestColumn2"]); TextBox2.Attributes["onchange"] ="javascript:SetRowChanged(" + e.Item.ItemIndex +")"; TextBox2.Attributes["onfocus"] ="javascript:CheckRowChanged('" + Repeater1.UniqueID +"', '" + TextBox1.ClientID +"', " + e.Item.ItemIndex +")"; TextBox TextBox3 = (TextBox)e.Item.FindControl("TextBox3"); TextBox3.Text = Convert.ToString(drvSampleData["TestColumn3"]); TextBox3.Attributes["onchange"] ="javascript:SetRowChanged(" + e.Item.ItemIndex +")"; TextBox3.Attributes["onfocus"] ="javascript:CheckRowChanged('" + Repeater1.UniqueID +"', '" + TextBox1.ClientID +"', " + e.Item.ItemIndex +")"; } }protected override void RaisePostBackEvent(System.Web.UI.IPostBackEventHandler sourceControl,string eventArgument) {if ((eventArgument !=null) && (eventArgument.Contains("SaveData$"))) {// Do nothing }else {base.RaisePostBackEvent(sourceControl, eventArgument); } }}

-- JScript.js

// JScript Filevar currentRowChanged = -1;function SetRowChanged(rowIndex){ currentRowChanged = rowIndex;}function CheckRowChanged(repeaterUniqueID, controlID, newRowIndex){if((currentRowChanged != -1) && (currentRowChanged != newRowIndex)) { saveInfo ='SaveData$' + controlID +'$' + currentRowChanged +'$' + newRowIndex; currentRowChanged = -1; __doPostBack(repeaterUniqueID, saveInfo); } }

web.config - project web config file

<configuration><configSections><sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"><sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"><section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/><sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"><section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/><section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/><section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/></sectionGroup></sectionGroup></sectionGroup></configSections><system.web><pages><controls><add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/></controls></pages><!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this affects performance, set this value to true only during development. --><compilation debug="true"><assemblies><add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/></assemblies></compilation><httpHandlers><remove verb="*" path="*.asmx"/><add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/><add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/><add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/></httpHandlers><httpModules><add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/></httpModules></system.web><system.web.extensions><scripting><webServices><!-- Uncomment this line to customize maxJsonLength and add a custom converter --><!-- <jsonSerialization maxJsonLength="500"> <converters> <add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/> </converters> </jsonSerialization> --><!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. --><!-- <authenticationService enabled="true" requireSSL = "true|false"/> --><!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and writeAccessProperties attributes. --><!-- <profileService enabled="true" readAccessProperties="propertyname1,propertyname2" writeAccessProperties="propertyname1,propertyname2" /> --></webServices><!-- <scriptResourceHandler enableCompression="true" enableCaching="true" /> --></scripting></system.web.extensions><system.webServer><validation validateIntegratedModeConfiguration="false"/><modules><add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/></modules><handlers><remove name="WebServiceHandlerFactory-Integrated"/><add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/><add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/><add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/></handlers></system.webServer></configuration>
Ok, here is a little secret about Update panel!Update panel posts back everything as in traditional .NET 1.1 Post back.Only at the rendering on the server does it realizes that it would only need to send what is in the update panel and sends only that part as response.So, your request is same as the post-back model. Only your response is minimized.I guess what you should be doing is making a call to Web Service or Web Method in a page and use JSON for serialization.

This way you would only send what you need to send and get back what is necessary...but you would have to write some Java Script :)


I can understand what you are saying to a certain degree. Indeed that is something to look into (and something to argue about with developers that don't like JavaScript) for performance increases. Thanks, Ravivb, for the info. I was not aware of JSON.

Unfortunately, there is still the root problem I'm having with AJAX. Somehow the server is not recognizing that it needs to refresh only a certain portion of the page. It is re-rendering everything. In the sample provided, the time outside the UpdatePanel is updated along with the time inside the UpdatePanel on every row change. Thus AJAX does not appear to be working at all on this page, as everything is posting back and being refreshed, rather than just the section inside the UpdatePanel.

Also, I don't understand why the JavaScript can't be loaded from a JavaScript .js file. It shouldn't make any difference if the JavaScript is embedded in the page or if it is being included from a file. But for some reason there is a difference.

Jeff


I have not followed your entire code to give proper answer on JavaScript problem.

But, if i were you, i would start at looking in to java script file path mapping to see if the path mapping is done right once the html is sent to client..

Next, try to debug java script to see what is going on. (you could use Firebug for FF or IE developer Toolbar fromhere

-good luck


Kalnir,

try looking into webservice. I have a few pages that are huge, doing postback on them is a pain in the b**t. Your webservice can be called from your javascript function.


Thanks, Ravivb and WishStar99. I just read up on JSON and the ASP.NET callback event technique, and I'm starting to work on constructing a test version of the page using the technique. I'll keep the webservice call in mind as well.

I'm not sure that will fix the problem I'm having with Repeater inside UpdatePanel, though. Any idea why the whole page is flashing instead of just the UpdatePanel region?


Heya, folks.

I want to thank Ravivb and WishStar99 for their help with this problem. The application was modified to use JSON and the ASP.NET callback event technique. The solution appears to be working fine and is fast enough to be acceptable to the end users.

The following articles helped me learn about JSON and how to work with it in .NET:

JSON (JavaScript Object Notation) data interchange format: http://json.org/


Glad it worked out...


Hi Jeff,

Can you show me in which article I can see some code sample for refreshing the gridView single row, as u did instead of using updatepanels.

I can t find some code sample where I refer the gridview or datagrid's single row.

Anyway, can u show us some code sample pls for doing what u did. i didn t find that on internet. I m not talking about calling the webmethod but especially m talking about the javascript DOM part that takes the result send by the webmethod and refreshes the datagrid or gridview's single row.

Thanks a lot.


Very interesting info on the JSON stuff.

I wanted to mention that I have almost successfully implemented a fully Ajax website using asp.net 2.0, however with one major problem. I have a Repeater object inside the UpdatePanel control, but everytime the Timer control kicks fires the asynch update it freezes up all of the page controls (i.e. hyperlinks, dropdownlists, etc.).

I have an update image that flashes with every Asynch update; and everytime the image appears I cannot click on any links nor access the dropdown lists. It's very frustrating.

Has anyone experiences this with a Repeater inside an UpdatePanel ? Any advice or ideas ?

Thank you very much,

Bob

AJAX UpdatePanel works on dev machine but still flickers on web server.

Hi Guys,

I have a master page, that has a ScriptManager and some "RoundCorner" controls. I also have a child page with a textbox and a FormView.

So I created an UpdatePanel, put my FormView inside the ContentTemplate, created the trigger and assigned to the TextBox's TextChanged event. (to an Async trigger).

When I run the app on the dev machine, it works wonders, no flickering and only the formview gets "refreshed". But as soon as I upload the code to the WebServer, the entire page gets refreshed everytime I change the value on the TextBox.

Am I forgetting to have something setup on the server side? I didn't find a "Deployment guide" for AJAX (If theres one, please point me to the right direction), so I figured that installing the MS Ajax 1.0 on the server would do it.

Thanks!

Marcelo

More info:

Just tried a small example, and again it does not work on the server side (both dates get updated):

<%@. Page Language="C#" AutoEventWireup="true" CodeFile="TestPage.aspx.cs" Inherits="TestPage" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server">From here, it is inside the panel <br /> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"> </asp:ScriptManager> <asp:UpdatePanel runat="server" ID="UpdatePanel1"> <ContentTemplate> <asp:Label ID="TestLabel" runat="server" Text=""></asp:Label> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" /> </Triggers> </asp:UpdatePanel><hr/>From here down its not inside the Panel<br /> <asp:Label id="Test2Label" runat="server" text="" /> <asp:Button ID="Button1" runat="server" Text="ClickHere" /> </form></body></html>

***********CS content

using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partialclass TestPage : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e) {TestLabel.Text = DateTime.Now.ToString();Test2Label.Text = DateTime.Now.ToString(); }}

Anyone has ideas?

Thanks!

Marcelo


Nobody at all?


Hello,

Take a look at my post and the solution we found:http://forums.asp.net/thread/1649057.aspx

Possibly your case is similar.


Hi there,

At first it seemed that I had my problem solved, since the properties show exactly the same as yours.. So I tried to change the property to true, but no luck, it still does a full refresh on the

server side..

I checked your sample site, and I it does a full refresh aswell.. what part of if should do a partial refresh?

Could you send me the code you have on your page Init?

this is what I've added on mine:

private void Page_Init(System.Object sender, System.EventArgs e) { ScriptManager1.SupportsPartialRendering =true; }

I'm getting frustrated with this...


Hi,

The partial refresh on our page (http://beta.easyquerydemo.com) works only for "Result" panel (at the bottom of the page). If you define some query using "Conditions" panel (for example: "Customer Company Name starts with A") and then click on "Update Result" button the result set should appear almost immediately and without updating the whole page.

As for code: we use exactly the same line of code as you published in your previous post.

Did you check the value of this property after assignment. Maybe it still is set to 'false' because of some limitations in browser which you use to access this page.


In this example of yours, both Labels get updated because you update the datetime in your Page_Load function.

Your Page_Load function should be like this:

Protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TestLabel.Text = DateTime.Now.ToString();
Test2Label.Text = DateTime.Now.ToString();
}
}

And your button to update the Label inside the updatepanel should call a function to update the datetime of that label.

Protected void UpdateLabel(object sender, eventargs e)
{
TestLabel.Text = DateTime.Now.ToString();
}


Hi,

What i'm doing is the following, on page_init i force the property to be true, and on page load i load all those variables into labels, just like you do on your sample site. It does in fact change that property to True. but the full refrensh still occurs.

Now I see the part that uses the update panel (The result on your site). And it actually works.

Do you have any other hint?

Correct me if I'm wrong but, theSupportsPartialRendering property is set based on:EcmaScriptVersion,SupportsCallback andW3CDomVersion; which are properties of HttpBrowserCapabilities that is assigned from a Request.Browser object.

That means that it is checking the Client's Browser capabilities, and nothing to do with the server itself right? If thats true, as long I use the same browser (IE7 for instance) it should not matter where that page is sitting at, it should bring the same value for SupportsPartialRendering...

Is my line of thought correct or I am missing something ?

Thanks a lot for the help you are giving me!


Hi there,

1. About "other hint". No I do not have it unfortunately. The only one thing I can suggest is to try add another UpdatePanel on your page and some simple controls into it (e.g. one button and one label) just for testing and see how it works. Another good idea will be to create another simple testing page using AJAX template in Visual Studio (if you use it) and see how it works on your server.

2. About the properties whichSupportsPartialRendering is based on: yes you are right, at least we understand this part of documentation exactly the same way.

Possibly we should send this request to Microsoft? There must be more conditions for partial rendering support except those ones described in documentation. I think there must be some requirements for server side.



Hey,

I will create a brand new example using the AJAX project template and report back my findings.

I agree, but I never done this before. Usually I can find a work-around for these type of issues, which doesn't seem to be the case right now. How should I proceed on submiting this to MS?

Regards


Hi again there,

More findings:

1. I created a brand new application and used the same sample as before, but this time I added the labels and forced SupportPartialRendering to true.

Amazingly the application worked just fine on the server side.

2. I've added a master page to this application and wired up the old "default.aspx" to the master page, moving the ScriptManager to the master page (and also the SupportPartialRendering portion)

Application stopped working.

3. I moved the ScriptManager (and SupportPartialRendering) back to the Default.aspx and removed from the master page.

Application still didn't work.

At this point I think is safe to conclude that: UpdatePanels will not work with master pages!!!?

PS: All the 3 situations work fine on the development machine.

Anyone has Master Pages + Update panels working properly on a production server?


We finally have solved the same problem. I think your case is similar.

Seehttp://forums.asp.net/thread/1653605.aspx for more info.


Hi korzh,

This is great, now it works like a charm! Thanks a lot for keeping me posted! Now, where in the documentation does it show anything about that property.. :P only a insider would know about it ..

Thanks a lot! Case closed!

Marcelo


Hi korzh,

This is great, now it works like a charm! Thanks a lot for keeping me posted! Now, where in the documentation does it show anything about that property.. :P only an insider would know about it ..

Thanks a lot! Case closed!

Marcelo

Ajax UpdatePanel with Wizard

Hi, I have a Wizard that have about 5 steps and in every step (page) I do have some tables, checkboxes, gridview...etc and I'm trying to Cut and Paste this wizard into Ajax for Ajax enabling, but it's giving me this error: "The ActiveStepIndex must be less than WizardSteps.Count and at least -1. For dynamically added steps, make sure they are added before or in Page_PreInit event" and when I took out the step(page) that have my gridview in it every thing worked fine!!!? So, Why is that? Thanks

Thanks

Hi,

It's hard to tell why without knowing your code, since it may be caused by some logic problems in your code.

Can you post a sample without relying on a particular database and class ?


I'm getting this error in Design time not run time, meaning once I cut and past my wizard into an Updatepanel the error comes up!!?

Thanks

AJAX UpdatePanel Refresh != Browser Refresh

Hey everyone. I've got a problem, I have a page that I want the data and buttons to refresh every 30 seconds. When I click the button, the data is recorded into a database and the button(s) are disabled until the next interval comes up. An interval is 5 mins even though the data will refresh every 30 seconds. That means that when the button is pushed, it should be disabled until the 5 min interval is up.

The problem I'm having is that even though my whole page is in the Update Panel, my buttons DO NOT re-enable after that 5 min interval, but my data labels DO. I have an indicator that changes at each 5 min interval and it is working, but my buttons are still disabled. I can refresh the page and the buttons are enabled...another thing is that after I press the button and it's disabled, I can refresh the page and the buttons still stay disabled as thy should until the next 5 min interval.

Is the entire Page_Load called on the AJAX Update Panel refresh? It doesn't seem like it since my code that enables/disables my buttons is not being called. Any ideas?

What is the full page refresh doing that the AJAX Update panel is not? I would just do a normal page refresh, but that looks bad and I'm also using the collapsable panels and the normal page refresh call would collapse all the panels. That would make the use of them, well, useless.

try call the update function of the updatepanel

<asp:UpdatePanel ID="Test" ...

code behind ... Test.Update()

if not then use javascript to set the buttons back to disabled = false;


The data refreshes fine still, but the buttons don't "reset."

Baseically, I have a function that is called for each button that looks in the database to see if a log has been made for this record. If there is not a log, the button is enabled, if there is a log, the button is disabled until the next interval. For some reason, my functions that check my buttons are not being called when the update panel is updated each 30 seconds. The functionality when the button is clicked works fine, but the buttons never enable again unless I hit the refresh in the browser to refresh the entire page.

I hope someone else has some suggestions as to what might be going on. Thanks!


Ok, here's the answer of why my "AJAX UpdatePanel Refresh != Browser Refresh"...

In my old version of the page, I have the default value of my buttons set to enabled. Each time the page refreshes, the default value is seen. In the AJAX update panel, the default value is not seen and therefore my buttons were not resetting to the default. My functions were assuming these would be enabled unless the log was found.

I hope this helps someone that might have the same problems in the future.

Ajax UpdatePanel Problem!

hey i made this news website using Asp.net .. and using Ajax UpdatePanel :www.raddar.co.il

the Top-Right News switches every 5 seconds using timer and updatepanel .. so if i was reading down page and it switches it will scroll straight away to top!

u can try it ... and see ...

scroll down and once it switchs (the news box in the top) it will scroll to top..

Thanks in Advance...

Set in page

<%@. Page smartNavigation="true" %>

<%@.PageMaintainScrollPositionOnPostback="true" %>


thx so much..


Thats niceSmile

Mark as answer if it's soved your problem,

So it will help for other people

Ajax UpdatePanel PageRequestMangerServerErrorException Problem

Hello and thank you for the opportunity to post my questions. I am having a heck of a time with the Ajax UpdatePanel.

My problem is as follows:

Everything works fine until there is some period of inactivity by the user (typically 2-3 minutes) and then when the user attempts to edit a row they receive the following message:

Sys.WebForms.PageRequestMangerServerErrorException: An unkown error occured while processing the request on the server. The status code returned from the server was:500

I have tried using the code listed below with the UpdatePanel UpdateMode Property using values of Conditional and Always with the same result.

What am I missing here? Do I need to add additional code to handle ViewState issues associated with the UpdatePanel?

Any assistance would be greatly appreciated! Thank you.


CODE USED:
<%@dotnet.itags.org. Page Language="VB" AutoEventWireup="true"
CodeFile="Default.aspx.vb" Inherits="_Default"
buffer="true" enableSessionState="true"
enableViewState="true" %>

<%@dotnet.itags.org. Register Assembly="AjaxControlToolkit"
Namespace="AjaxControlToolkit"
TagPrefix="ajaxToolkit" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Ajax Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" AutoGenerateEditButton="True" DataKeyNames="ID"
DataSourceID="SqlDataSource1" GridLines="None" PageSize="20">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:BoundField DataField="Class" HeaderText="Class" SortExpression="Class" />
<asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
UpdateCommand="UPDATE [Master] SET [LastName] = @dotnet.itags.org.LastName, [FirstName] = @dotnet.itags.org.FirstName,
[Type] = @dotnet.itags.org.Type, [Class] = @dotnet.itags.org.Class, [Status] = @dotnet.itags.org.Status
WHERE [ID] = @dotnet.itags.org.original_ID AND [LastName] = @dotnet.itags.org.original_LastName AND
[FirstName] = @dotnet.itags.org.original_FirstName AND [Type] = @dotnet.itags.org.original_Type AND
[Class] = @dotnet.itags.org.original_Class AND [Status] = @dotnet.itags.org.original_Status">
<UpdateParameters>
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="Type" Type="String" />
<asp:Parameter Name="Class" Type="String" />
<asp:Parameter Name="Status" Type="String" />
<asp:Parameter Name="original_ID" Type="Int32" />
<asp:Parameter Name="original_LastName" Type="String" />
<asp:Parameter Name="original_FirstName" Type="String" />
<asp:Parameter Name="original_Type" Type="String" />
<asp:Parameter Name="original_Class" Type="String" />
<asp:Parameter Name="original_Status" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

Try to set EnableEventValidation="false" in <%@. Page %> tag..

see results if it solves the problem...


Thank you for taking the time to respond to my question. Yes I did try that and no it did not work. I also tried EnableViewStateMac = False and other suggestions outlined in Microsoft's Knowledge Base Article # 829743 entitled "Troubleshooting the "View State is invalid" error with ASP.NET" with no success either.

I have tried searching the blogs and other sites of interest releated to Ajax. The only post which I have seen that comes the closest to addressing this issue ishttp://www.openjs.com/articles/ajax/session_timeout.php but it addresses generic Ajax and not the flavor supported by Microsoft.

Due to the fact that I am brand new to using Ajax of any kind, I tried posing on this site to attempt to find an anwser to this vexing problem.

Thank you again for taking the time to respond to my post.


Thanks...I read the article about session_timeout...

Have you tried any other solution...


Hello again. Yes, I have tried a number of things. One method that appears to work is putting a timer on the page and setting the tick for every 2 minutes or so. When the timer reaches the alarm point, it refreshes the page. The problem seems to go away. However, using this type of method could have serious performance issues if deployed accross a large number of sites and pages being hosting on the same server.

So there definately is a relationship with this problem and the viewstate. By causing the page to refresh it resets the viewstate. There must be some value caused by the async postback(s) that is offending the validation at the server a some later time. It could also be releated to the fact that the session on the server has expired and it can't find anything to refer to so it blows up.

I love being a developer but sometimes stuff like this just drives me nuts!

Any thoughts you would like to add?

Thanks for your interest in helping to solve this problem for me.


Hiwindyman42

This happens when the machineKey used to encrypt/decrypt the viewstate was changed, and more likely this will happen if you keep the page idle for a long time. To avoid this, you need to have a static machineKey.

Check this articlehttp://blog.g9th.com/2007/01/14/unable-to-validate-data-at-systemwebconfigurationmachinekeysectiongetdecodeddata.aspx

Let me know if you need more info.
You can also see this thread for more help:http://forums.asp.net/t/1115331.aspx

Thanks


Thanks Jin-Yu Yinfor providing the more details...Smile


Thank you for your response! I appologize for the delay in responding but I wanted to fully test your suggestion before replying to your post. I am very pleased to report that your suggestion does in fact FULLY FIX THE PROBLEM! The only thing that is a little puzzling however is that one of the links you provided (The Experts) said that making the MACViewState value = False has the same effect as providing a static machine key. I had tried this ealier but it was unsuccessful.

Thank you both for taking the time to provide assistance. I hope to return the favor in kind sometime in the future.

Ajax UpdatePanel does not return MS-SQL errors??

I have a datagrid wrapped in an UpdatePanel. When I try adding or editing a row that violates a check constraint, I recieve the ridiculous Sys.WebForms.PageRequestManagerPerserErrorException: the message received from the server could not parsed... instead of the MS-SQLL error message.

Is there a way to rectify this behaviour?

TIA

Hi,

Please refer to this for the reason of the error:

http://siderite.blogspot.com/2007/02/aspnet-ajax-and-responsewrite-or.html

Hope this helps.

NOTE:This response contains a reference to a third partyWorld Wide Web site. Microsoft is providing this information as a convenienceto you. Microsoft does not control these sites and has not tested any softwareor information found on these sites; therefore, Microsoft cannot make anyrepresentations regarding the quality, safety, or suitability of any softwareor information found there. There are inherent dangers in the use of anysoftware found on the Internet, and Microsoft cautions you to make sure thatyou completely understand the risk before retrieving any software from theInternet.


I'm not sure about what is the inner problem of your application.
But I also face this kind of problem - 'Sys.WebForms.PageRequestManagerPerserErrorException:'. So far I
understand this happen when there is some unrecongnize html render or event occurs. I'm also not very clear.
But I solve the issue by set the attribute EnableEventValidation="false" in the ASPX page, where I place my UpdatePanel.Thanks
I'm not sure about what is the inner problem of your application.

But I also face this kind of problem - 'Sys.WebForms.PageRequestManagerPerserErrorException:'. So far I
understand this happen when there is some unrecongnize html render or event occurs. I'm also not very clear.

But I solve the issue by set the attribute EnableEventValidation="false" in the ASPX page, where I place my UpdatePanel.

Thanks

Thanks Raymond,

Yep. You can't write to the response stream when using AJAX.


Here is one more link

http://weblogs.asp.net/leftslipper/archive/2007/02/26/sys-webforms-pagerequestmanagerparsererrorexception-what-it-is-and-how-to-avoid-it.aspx

AJAX UpdatePanel and Validators - Framework Updated?

Hi Folks,

I bumped into the updatepanel/validator control issue yesterday and solved the problem by grabbing the updated validators project as per the pinned post at the top of this forum (http://forums.asp.net/t/1066821.aspx).

That said, in the post and in Scott Guthrie's blog there is mention of an official patch to ASP.NET 2.0 to fix this issue which would go out via windows update. Did this ever happen? My own dev box certainly doesn't seem to be fixed (hence having to use the compatibility validators downloaded from mattgi's site).

Cheers

Kev

I think it has because I do not have the Validator issue and I am not using the Validator library anymore. But do not hold me to it, I may have just prayed real hard for effective validation. I also like the MaskedEditValidator control too, you should check it out.


I feel like a real shoe for using someone elses code and not understanding what it's doing...

I hope I can find time to view this guys source... :(


Wow, this actually did not fix my issue -- but I know I'm using validators in the an updatepanel an getting the same issue. Grrr...


Hello.

if i'm not mistaken, you'll only get compatible validators on the 3.5 framework since the validators of 2.0 were never updated to be compatible with the updatepanel.

Ajax UpdatePanel and onload=JavaScript Function

Hi,

I am trying to work through a program but getting really stuck.

I have a asp.net (aspx) page which shows a table of data from a SQL query to the DB. This all works fine. I have a <body onload='resizediv()';> which calls a JavaScript code that resizes the DIV that the table data is displayed in - just so it adds a scrolling area if the table data is >400px deep.

This all works just fine and as it should.

So I thought I would Ajax enable it with a panelupdate control which I wrapped around the Table and DIC that displays the data from the DB. Again this all works as it should - clicking on my "refresh" control button the ajax re-loads the table data without the nasty page flicker.

BUT - my onload='resizediv();' JS function is not called when the updatepanel is refreshed ... it is called the first time the page loads but not when I click on the button control that does the refresh of the panel. Is there anyway to make this JS function fire each time the Ajax panel is updated ?

Apologies if this description is hard to understand, but I am very new to asp.net and Ajax ... :(

Thanks in advance ...

Ro

No ideas on how this could be done ? or am I just looking at this from the wrong angle ?

Thanks

Ro


Instead of using onload=..., try:

<script type="text/javascript">
Sys.Application.add_load(function() { ... });
</script>

If memory serves, the Load event should fire on initial page load as well as any async postbacks.


Steve,

Excellent reply, just tried this and indeed it works with load and partial page loads.

This will help me out no-end ....

Many thanks,

Ro

AJAX UpdatePanel - Textbox focus question - simple example

I have run across an issue recently while incorporating AJAX into one of my applications. The issue demonstrates either my fundamental lack of understanding about how this technology works, or a problem in my implementation of it. I have created an bare-bones simple example to demonstrate what I'm seeing. I know how to remedy the problem, but I'd prefer the discussion center around *WHY* it's happening.

Here are the details. Consider a project with a default.aspx. That page has two controls, Button1 and PlaceHolder1. The project also contains as usercontrol, uc1.ascx, which simply contains a TextBox control, TextBox1. The click event of Button1 dynamically loads uc1 into the placeholder via the Page.LoadControl method. All I really want to do is set focus to to TextBox1 after the control is loaded. Without the UpdatePanel, I can do it two ways. I can either put TextBox1.Focus(); in UC1's page load event, or I can register a startup javascript to find the textbox and use its focus() method. Either way works fine. See example code below.

Now introduce UpdatePanel. Enclose Button1 and PlaceHolder1 in the same UpdatePanel. The result, no focus to the textbox. Move Button1 outside of the UpdatePanel, focus will work. Fundamental question is - WHY? Why does it matter where that button control is in relation to the Placeholder and UpdatePanel. I've done a lot of searching on this topic and I've found lots of questions but not many answers. Here's the code I'm using, to get focus to work correctly, move Button1 outside of the UpdatePanel:

Default.aspx

<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:UpdatePanel ID="up1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Load UC1" OnClick="Button1_Click" />
<br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

Button1_Click Event:

protected void Button1_Click (object sender, EventArgs e)
{
Control ctrl = new Control();
this.PlaceHolder1.Controls.Clear();
ctrl = Page.LoadControl("uc1.ascx");
ctrl.ID = "DynamicCtrl";
this.PlaceHolder1.Controls.Add(ctrl);
}

uc1.ascx:

<%@dotnet.itags.org. Control Language="C#" AutoEventWireup="true" CodeFile="uc1.ascx.cs" Inherits="uc1" %>
UserControl 1 <br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

uc1.ascx.cs:

using System;
using System.Web.UI;

public partial class uc1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
//use either of these two lines in the example
//this.TextBox1.Focus();
ScriptManager.RegisterStartupScript(this, typeof(UserControl), "focus", "document.getElementById('DynamicCtrl_TextBox1').focus();", true);
}
}

OK, now I'm really annoyed and I'm punchy enough to reply to my own posts. In reading a multitude of UpdatePanel/focus related threads, I found a snipped of javascript code that I though I'd try. I inserted the following section of code in the default.aspx contained in my original post. First I inserted it in the head section of the page and that resulted in the dreaded 'Sys' is undefined message. Then I moved the javascript *below* the scriptmanager and the page loaded with no errors. Here's the code I now have inserted in default.aspx just before the end form tag:

<scripttype="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(pageLoaded);
function pageLoaded(sender, args)
{
if (args.get_panelsUpdated().length > 0)
{
$get('DynamicCtrl_TextBox1').focus();
}
}
</script>

So here's what is making me punchy. I try the page in IE 6 & 7, no focus to the textbox. Try in FireFox, *FOCUS WORKING CORRECTLY*!! Now that's annoying. Could someone please take a stab at either reproducing what I'm seeing or possibly explaining it?? Thanks.

...BillH


I am developing a liking to responding to my own posts - makes me feel loved.

OK, so a few minutes ago I tried something that made my above scenario work. Don't know why, but now I have textbox focus in both IE and Firefox and the solution fits within the context of the project I'm working on. I don't need any startup scripts or Focus() methods on the textbox control.

What I did was create a public accessor for TextBox1 in the user contol codebehind as such:

public TextBox t
{
get
{
return this.TextBox1;
}
}

Then I added the following one line to the Button1 click event (after the dynamic control is added to the placeholder):

this.ScriptManager1.SetFocus(((uc1)ctrl).t.ClientID);

Viola. Textbox focus in both IE7 and Firefox. No idea why, take it for what it's worth.

...BillH


Thank you so much!

I've been working on this issue for a while now... I couldn't get any of my TextBoxes inside any UpdatePanels to set focus.

The solution seems like you just have to set the focus like this:

this.ScriptManager1.SetFocus(TextBox1);

and voila it works.


Yep, that works when your textbox is on the page that's loaded. In my case, it was in a user control that was being dynamically loaded via button click events. At any rate, while your above sample would work when the control is within the same form as the ScriptManager, I would strongly suggest you explicitly pass the SetFocus method the ClientID of the control:

this.ScriptManager1.SetFocus (this.TextBox1.ClientID);

In that way if you go back and reuse this code somewhere and you have a textbox on a usercontrol or within some other dynamically loaded control it would still work.

...BillH


Many many thanks for your inputs! It really worked!Smile

AJAX update without updating viewstate

Hey,

Does someone know if it's possible to update contents on the webform without sending the viewstate and other useless stuff?

Sometimes I update only one value of a textbox. An update of the viewstate is not necessary. This is a problem; sending the viewstate again makes the reponse to slow . (it takes >500ms, and that is too slow)

Withajaxpro the response takes ~40ms. But I don't want to use both frameworks (I use ajax.asp already for the ajaxtoolkit)

I tried:

RegisterDataItem without an updatepanel update.RegisterClientScriptBlock with an updatepanel update


ps. I don't want to disable or reduce the viewstate, that isn't possible.

Hi

You can use page methods. No ViewState is transferred when invoking page method. Then update your TextBoxes with JavaScript.

Seehttp://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx

-yuriy
http://couldbedone.blogspot.com


AH, that looks interesting. It look likes the ajaxpro method.Smile

I will post later some comparison times.

ajax update progress control with FileUpload control

Hi,

There has been a lot of posts about this in other communities as well as in asp.net forum.But I am not getting a correct picture.

By default,the fileupload and Ajax update panel does not go together,I am using a trigger where the postback trigger id is pointing to a button,which initiates the file upload.I have put an update progress control also.

But I am not seeing the update progress and the ajax behaviour is not consistent(actually its not getting).Can someone throw a light into this?

Regards

Ajith

Hi,

since you have activated the postback trigger of the update panel,it will act as a normal form and you will lose the benefit of asynchrounous effet.So,the update progress control will have no effect in this case since all the page is posted back.

In fact,this the only walkaround (that I have found) to use the fileuplod control inside an update panel.

Hope that this help you.


Hi,

So there is no point in using ajax technology there right.....

Regards

Ajith

Ajax Update Progress

Hello, I need to have three ajax update progress controls on one page. The problem im having is that when an event is triggered for any of the update panels none of the update progress controls appear. What am I doing wrong. Heres my code:

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Image ID="SiteOneThumb" runat="server" Height="158px" Width="210px" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="SiteOneTextBox" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<img src="http://pics.10026.com/?src=Images/loading.gif" /> <br />
Retrieving Thumbnail...
</ProgressTemplate>
</asp:UpdateProgress
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:Image ID="SiteTwoThumb" runat="server" Height="158px" Width="210px" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="SiteTwoTextBox" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress2" runat="server" AssociatedUpdatePanelID="UpdatePanel2">
<ProgressTemplate>
<img src="http://pics.10026.com/?src=Images/loading.gif" /> <br />
Retrieving Thumbnail...
</ProgressTemplate>
</asp:UpdateProgress
<asp:UpdatePanel ID="UpdatePanel3" runat="server">
<ContentTemplate>
<asp:Image ID="SiteThreeThumb" runat="server" Height="158px" Width="210px" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="SiteThreeTextBox" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress3" runat="server" AssociatedUpdatePanelID="UpdatePanel3">
<ProgressTemplate>
<img src="http://pics.10026.com/?src=Images/loading.gif" /> <br />
Retrieving Thumbnail...
</ProgressTemplate>
</asp:UpdateProgress>

Thanks!

Hi.

Why dont you use only one Updatepanel and updateprogress control and bind different asynchronous events to this update panel. And it shud work.

If i am in wrong direction, please elaborate more.

Cheers


Hi I think it cannot be done currently. Atleast i think so . I have tried it. Probably you can use any no of updatepanels but a single updateprogress control.We can set this update progress control to monitor all the partial rendering happens in the entire page.To implement that just remove the AssociatedUpdatePanelID property. By default it will watch the entire page for all Partial renderings.

hello.

well, if i'm not mistaken, i'm under the impression that updateprogress will only work if the postback is started by a control placed inside an updatepanel. anyway, not all is lost :)

you can hande the beginRequest and endRequest client event fired the by the client pagerequestmanager object that is inserted on the page when you use updatepanels. during the beingrequest, you need to get a reference to the control responsible for the async postback and you need to map it to the "correct" updateprogress control. after doing this, you only need to show the contents of that updateprogress by setting the display (or visible) css property of it. dyuring the endrequest event, you need to hide the contents of the panel again.

AJAX update panel updating all panels!

Hey there, I have 2 updated panels on a page update panel1 and update panel2.

One is triggerd by a list box and the other is triggered by an image button,, the only problem is although each trigger is assigned to their respective list boxes, whenever a trigger is activated it refreshes both update panels, which is not what I want.

This is my update panel refreshed by the image button

<asp:UpdatePanelID="UpdatePanel2"runat="server"><ContentTemplate><TABLEid="Table6"style="WIDTH: 208px; HEIGHT: 248px"cellSpacing="1"cellPadding="1"width="208"border="0"><TR><TDstyle="HEIGHT: 197px; width: 206px;"vAlign="top"align="center"><BR><asp:listboxid="ListBox1"runat="server"Width="143px"Font-Names="Arial"AutoPostBack="True"Height="232px"></asp:listbox></TD></TR></TABLE></ContentTemplate><Triggers><asp:asyncPostBackTriggerControlID="SearchButton"EventName="Click"/></Triggers></asp:UpdatePanel>

Any thoughts on this?

Thanks in advance

You need to set the UpdateMode on the UpdatePanels to "Conditional". By default it is set to "Always" which means it will be updated on any postback.

Ajax Update Panel question

Is it possible to place an update panel (or some other ajax control) on a non .aspx page? I am trying to build a poll application to use on our content pages. Unfortunately our content pages are just straight up html pages and do not run through the .net server. In fact asp.net isn't even installed on that server and likely can't be. Is it possible to have something on an html page redirect itself to the asp.net server?

I know this can't be done with regular asp.net controls but i thought perhaps the Ajax update panel would work?


If that wouldn't work is there another alternative, that still uses the .net framework?

I've seen other polling applications that let you copy and paste a simple line of javascript code onto their blogs or html pages,etc. And this piece of javascript communicates with the poll service. I was wondering if asp.net had a similar solution.

Jay

Hey,

Not on HTML pages no, only with ASPX pages. If you are using HTML, you could download the client solution they created off of the ajax.asp.net. It is the client-side libraries they used, which you can use that in HTML no problem.


Take a look at the Microsoft Ajax Library

http://ajax.asp.net/downloads/default.aspx

http://aspnetresources.com/blog/ms_ajax_cheat_sheets_batch1.aspx

ok thanks. I looked at these and its a start, although it looks pretty overwhelming for a newbie. I don't know where to begin.

I believe this is the online documentation for the client libraries correct?

http://ajax.asp.net/docs/ClientReference/default.aspx

Off-hand would you happen to know of any websites or tutorials or that would explain how to use the client libraries a little better?

Jay


This blog entry has an example and some links

http://blogs.msdn.com/brada/archive/2006/10/23/microsoft-ajax-library-at-the-ajax-experience.aspx

In fact asp.net isn't even installed on that server and likely can't be.

AJAX.net is based on theXMLHttpRequest, which works only for the same domain, AKA sandbox. Depending on your network anupdatepanel based on MicrosoftAjax.js may be very complex to implement. It is easier to haveHTML and.net on one server only.

Is it possible to have something on an html page redirect itself to the asp.net server?

Solution A: you can (re-)direct the user to your poll server in using a simplelink or the Javascriptlocation object.


B and C are likely the paths i will take i think. I've played around with the IFRAME and it seems to work well. I was trying to avoid it but i guess its not so bad. Thanks.

J

AJAX Update Panel Problems

Hi,

I'm converting an existing site to use the AJAX toolkit. So far the only problems I've had have been the usual teething problems when learning a new technology. Now though, I'm having a problem with using one of my existing classes from code invoked from a control in an update panel. It's always worked fine until using the update panel. I've pasted the code below (i got it off the web by the way). If i call it from a control outside of an update panel i have no problems.

The error message i'm getting is as follows:

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(). response filters, HttpModules, or server trace is enabled.
Details: Error parsing near 'leteWeek"));
});
|<script language='ja'.

Any help/pointers would be much appreciated.

publicclassMessageBox

{

privatestaticHashtable m_executingPages =newHashtable();

private MessageBox(){}

publicstaticvoid Show(string sMessage )

{

// If this is the first time a page has called this method then

if( !m_executingPages.Contains(HttpContext.Current.Handler ) )

{

// Attempt to cast HttpHandler as a Page.

Page executingPage =HttpContext.Current.HandlerasPage;if( executingPage !=null )

{

// Create a Queue to hold one or more messages.

Queue messageQueue =newQueue();

// Add our message to the Queue

messageQueue.Enqueue( sMessage );

// Add our message queue to the hash table. Use our page reference

// (IHttpHandler) as the key.

m_executingPages.Add(HttpContext.Current.Handler, messageQueue );

// Wire up Unload event so that we can inject

// some JavaScript for the alerts.

executingPage.Unload +=newEventHandler( ExecutingPage_Unload );

}

}

else

{

// If were here then the method has allready been

// called from the executing Page.

// We have allready created a message queue and stored a

// reference to it in our hastable.

Queue queue = (Queue) m_executingPages[HttpContext.Current.Handler ];

// Add our message to the Queue

queue.Enqueue( sMessage );

}

}

// Our page has finished rendering so lets output the

// JavaScript to produce the alert's

privatestaticvoid ExecutingPage_Unload(object sender,EventArgs e)

{

// Get our message queue from the hashtable

Queue queue = (Queue) m_executingPages[HttpContext.Current.Handler ];if( queue !=null )

{

StringBuilder sb =newStringBuilder();

// How many messages have been registered?

int iMsgCount = queue.Count;

// Use StringBuilder to build up our client slide JavaScript.

sb.Append("<script language='javascript'>" );

// Loop round registered messages

string sMsg;while( iMsgCount-- > 0 )

{

sMsg = (string) queue.Dequeue();

sMsg = sMsg.Replace("\n","\\n" );

sMsg = sMsg.Replace("\"","'" );

sb.Append(@dotnet.itags.org."alert( """ + sMsg +@dotnet.itags.org.""" );" );

}

// Close our JS

sb.Append(@dotnet.itags.org."</script>" );

// Were done, so remove our page reference from the hashtable

m_executingPages.Remove(HttpContext.Current.Handler );

// Write the JavaScript to the end of the response stream.

HttpContext.Current.Response.Write( sb.ToString() );

}

}

Hi,

you can't use Response.Write during a partial postback. The reason is that the response sent after a partial postback has a special format (you could useFiddler to see it). If you use Response.Write, you're directly writing to the response stream and corrupting the response's format.

To inject JavaScript during a partial postback, you should use the static RegisterXXX methods of the ScriptManager control.


Thanks for that. I found aa article elsewhere explaining how to use the script manager and I've got that working fine. Thanks for your help.

AJAX Update Panel problem with IE6

On my site I have an asp:dropdownlist next to an asp:image. Ive put both of these within an asp:updatepanel. When the selected item in the dropdownlist is changed the panel updates with a new image depending on the selected item. This all works fine on FireFox and IE7, however on IE6 I get the following error:

Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 12019

As a temporary fix I have removed the updatepanel tag meaning the page now reloads every time and it works fine. However it would be much better if this didn't have to happen. Has anyone seen this error before, and if so how can I stop it from happening. Why does it happen on only IE6?

Thanks,

Curt.

Maybe this can help: http://forums.asp.net/t/1123365.aspx

Two last replies are specially interesting Wink


Thanks for the link bsevo.

I have been testing the site using IE6 on an OS which also has IE7 so maybe thats why its not working? I'll have to try and find an OS which has the 'real' IE6.

Ajax Update Panel not working...

hi,

I am using the below coding in Inline code..

<

body><formid="form1"runat="server"><div> <asp:ScriptManagerID="ScriptManager1"runat="server"></asp:ScriptManager> <asp:UpdatePanelID="UpdatePanel1"runat="server"><ContentTemplate>

<asp:ButtonID="Button1"runat="server"OnClick="Button1_Click1"Text="Button"/><asp:LabelID="Label1"runat="server"Text="Label"></asp:Label></ContentTemplate></asp:UpdatePanel>

</div></form>

</

body>

in code behind

protected

voidButton1_Click(object sender,EventArgs e)

{

Label1.Text =

"Refresh at " & DateTime.Now.ToString();

}

But when I run this page and click on the Button The Page is Posted back again and again..

Please Give quick answer it's urgent......

Thanks

Rocky..

Hi,

did you make the necessary changes to the web.config in order to enable ASP.NET AJAX?


yes ,

In web.config i fix

<

xhtmlConformancemode="Legacy"/>

but i still get the problem...


Hi,

did you apply all the other settings? Specialized sections, handlers etc. ?


will you please tell me briefly about all these settings so that my update panel will work...

if possible then code please for web.config file...

Thanks

Rocky


Hi,

please check theonline documentation topic.

As an alternative, you could compare your web.config with the one of the ASP.NET AJAX-enabled website installed as a Visual Studio template, and make the corresponding changes.


Any other setting I have to do except web.config documentation file in the web site and in eb.config??

Thanks

Rocky


Hi,

it should be enough. Be sure that you've referenced the System.Web.Extensions assembly in your website.

AJAX Update Panel Issues with Master Pages

Hello all, I am having issues using AJAX on my aspx content pages. I have a Master Page that contains a Script Manager and I want to use an Update Panel on some of my content pages. When I do this my aspx content page does not recogize any element on the page that is in the Update Panel, nor does it recognize the Update Panel. It underlines every control on the page and displays "unknown element" errors. I can still build my solution and run the app with no problems, and the AJAX seems to function correctly, but when I view the source code of the aspx page I get errors. If I try and change properties in Design view my Visual Studio locks up. If I use an Update Panel or any other Ajax extensions on a page that is not a content page of a Master Page everything works perfectly.

Is this a common problem with Master Pages? Is there a solution? I tried to search for this problem but did not turn many results. Any help or direction would be appreciated! This makes it very hard to develop. I am using Version 1.0 of ASP.Net AJAX.

Yes it is an issue a lot of people see I would assume. I just answered another post in regards to this here

http://forums.asp.net/thread/1623913.aspx

AjaxButter


Installing SP1 for Visual Studio 2005 fixed this problem.

Ajax update panel is resetting text box values that were calculated with javascript

Dear all,

I have some text boxes which hold numbers which are calculated from other text boxes using javascript. This works fine.

My problem is that I have put some these boxes (as well as many other controls etc) inside an Ajax Update Panel and as soon as the panel updates, it resets my textboxes back to their default value. This does not happen after a postback without the update panel.

Can anyone tell me why this is and how I may fix it?

Thanks for your help.

It sounds like the calculation might be taking place on the client-side after the partial postback has already begun. What triggers the calculation? What triggers the partial postback of the UpdatePanel?


The clientside calculation has already taken place and is visible on screen. This is done my an onchange event on the textboxes. The AJAX partial postback in the update panel is done afterwards only on the press of a button.

Thanks


Are the changes visible when the postback begins or just when it ends? With UpdatePanels, client side changes that happen during the partial postback will be lost when the async postback completes. For instance, if someone hits enter in one of the TextBoxes, would the partial postback initiate before the client side calculation completes?

Another common problem is code running in Page_Load that resets the TextBoxes each postback. You might consider stepping through the entire partial postback with the debugger and make sure that no unexpected code is being run.

If it's none of that, post some code. I'll take a look at it for you.


The changes are visible when the postback begins. The whole thing works perfectly if it is not in an update panel There is nothing in the page_load to reset anything.

The page/code is large to I have put an example below. Put a 1 in the first text box and tab and the second textbox will display a converted amount. Click the button to postback and the values will stay. Put all the controls in an update panel and the postback resets my calculated amount.

I'm so stuck here. Really appreciate your help.

thanks

<%@.PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

<title>Example</title>

<scriptlanguage="javascript"type="text/javascript">

function convertMeasures()

{

convertedWeight=document.getElementById("<%=MetricWeight.ClientID %>");totalWeight=document.getElementById("<%=Weight.ClientID %>").value;

lbsinkilos=2.20462262;

convertedWeight.value=totalWeight/lbsinkilos;

}

</script>

</head>

<body>

<formid="form1"runat="server">

<div>

<asp:TextBoxID="Weight"runat="server"onchange="convertMeasures();"Style="position: relative"></asp:TextBox>

<asp:TextBoxID="MetricWeight"runat="server"Style="position: relative"></asp:TextBox><br/>

<br/>

<asp:ButtonID="Button1"runat="server"OnClick="Button1_Click"Style="position: relative"

Text="Postback Nothing"Width="137px"/>

</div>

</form></body>

</html>


I just tried using the Infragistics Update Panel and it works fine. The values are retained after postback. Unfortunalty I'm not allowed to use infragistics in this application. :-(

thanks


Using this code, I wasn't able to reproduce.

<%@. Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Example</title
<script language="javascript" type="text/javascript">
function convertMeasures()
{
convertedWeight=document.getElementById("<%=MetricWeight.ClientID%>");
totalWeight=document.getElementById("<%=Weight.ClientID%>").value;
lbsinkilos=2.20462262;
convertedWeight.value=totalWeight/lbsinkilos;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server" ID="sm1" />
<asp:UpdatePanel runat="server" ID="up1">
<ContentTemplate>
<asp:TextBox ID="Weight" runat="server" onchange="convertMeasures();" />
<asp:TextBox ID="MetricWeight" runat="server" /><br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Postback Nothing" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Try that code and see if you can reproduce the problem that you're having.

Hello

ok - I have found what it is that causes the problem, although not the answer. The problem only occurs when I make the MetricWeight textbox readonly(as I have been to stop users altering the result of the calculation). Code below. Strangly this now seems to happen even if there is no Ajax. Do you know how I can stop this?

Thank you for your time

<%@.PageAutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default"Language="C#" %>

<%@.RegisterAssembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

Namespace="System.Web.UI"TagPrefix="asp" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headid="Head1"runat="server">

<title>Example</title>

<scriptlanguage="javascript"type="text/javascript">function convertMeasures()

{

convertedWeight=document.getElementById("<%=MetricWeight.ClientID %>");

totalWeight=document.getElementById("<%=Weight.ClientID %>").value;

lbsinkilos=2.20462262;

convertedWeight.value=totalWeight/lbsinkilos;

}

</script>

</head>

<body>

<formid="form1"runat="server">

<div>

<asp:ScriptManagerID="sm1"runat="server">

</asp:ScriptManager>

<asp:UpdatePanelID="up1"runat="server">

<contenttemplate>

<asp:TextBoxID="Weight"runat="server"onchange="convertMeasures();"/>

<asp:TextBoxID="MetricWeight"runat="server"BackColor="LightGray"ReadOnly="True">0</asp:TextBox>

<asp:LabelID="Label1"runat="server"Style="position: relative"Text="Label"></asp:Label><br/>

<br/>

<asp:ButtonID="Button1"runat="server"Text="Postback Nothing"/>

</contenttemplate>

</asp:UpdatePanel>

</div>

</form>

</body>

</html>


That'd do it. From theTextBox.ReadOnly documentation:

The Text value of aTextBox control with theReadOnly property set totrueis sent to the server when a postback occurs, but the server does noprocessing for a read-only text box. This prevents a malicious userfrom changing aText value that is read-only.


Probably the easiest workaround is to remove the ReadOnly attribute from the TextBox and add: onfocus="this.blur();"

Alternatively, since the values are still posted to the server, you could reassign each TextBox's value in each postback, using MetricWeight.Value = Request["MetricWeight"].


Thanks for your help. I also used the OnKeyUp event instead of the OnChange to make it work a little better too.

Thanks again!

AJAX Update Panel in ASCX Control

Hi All - I have searched for and read about every post concerning using the AJAX library in an ASCX control and I am at a loss. I sure hope someone can help me figure out how to get it to work.

I am dynamically adding ASCX controls to my page using the Page.LoadControl method and it works fine. I have an Update Panel containing a TextBox control that I try to access from the ASPX page but it says it does not exist. I even have a property that specificallt returns the text box for me. When I Debug I look at the Update Panel and it is there with one control. That control is a Content Template and it has 0 controls. I don't know where my TextBox has gone. I wanted to get a handle on it so that I could add an event handler.

I have tried several other approaches inclusing dynamically adding the control to the update panel at run time and that failed miserably. Does anyone have any suggestions?

Any help is appreciated. Thanks!

DK

Try creating your dynamic controls in Page_Init event handler (same signature as Page_Load). Most problems like this have to do with the fact that code executed on postbacks, such as button click handler, is called before Page_Load, thus before your dynamic controls are recreated. Another good reason to have your controls created in Page_Init: only then they participate in ViewState restoration (as long as you assign them with the same ID in all the roundtrips).

Thanks for the suggestion. I will give that a try and post back the results.


That did not work unfortunately. The TextBox is still not there when I try to add a Handler.

I did want to add some additional information that may or may not help. My TextBox controls on the ASPX page that are inside of Update Panels work perfectly so my web and everything else is configured properly. It is just the use in an ASCX control that is not working.

I have read many other posts in this newsgroup with the same issue but I am not seeing anyone posting a real resolution as far as I can tell. Does the AJAX team at MS have any perspecitve or guidance on this?

Thanks,

DK


Could you please submit a minimal code sample where the problem appears? I'd give it a try...

I am having the same problem, this is some sample code:

In the User Control ascx

<%@.ControlLanguage="VB"AutoEventWireup="false"Inherits="ucCalendarWithTextBox"Codebehind="ucCalendarWithTextBox.ascx.vb" %>

<%--Dynamic atlas updatepanel is possible as of June 2006, we still haven't download that yet--%>

<%@.RegisterAssembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

Namespace="System.Web.UI"TagPrefix="asp" %>

<

asp:UpdatePanelID="up2"runat="server"><Triggers><asp:AsyncPostBackTriggerControlID="CalendarPicker"EventName="SelectionChanged"/></Triggers><ContentTemplate><asp:TextBoxID="TxtDate"runat="server"Width="120"ReadOnly="false"AutoPostBack="true"></asp:TextBox></ContentTemplate>

</

asp:UpdatePanel>

In an aspx page

Dim

calFromAs UcCalendarWithTextBox = Page.LoadControl("../UcCalendarWithTextBox.ascx")

The problem is:

calFrom.TxtDate = Nothing. i.e. I can't find the controls in my contenttemplate


Sure - Here is the code for my ASX control:

-----------------------------

<%

@.ControlLanguage="vb"AutoEventWireup="false"CodeBehind="MCAProducerBasePercentControl.ascx.vb"Inherits="MCAWeb.MCAProducerBasePercentControl" %>

<

tableid="tblProducerBasePercent"runat="server"><tr><tdalign="left"style="width: 75px"><asp:UpdatePanelID="upProducerID"runat="server"><ContentTemplate><asp:TextBoxID="txtProducerID"runat="server"Width="75px"></asp:TextBox></td></ContentTemplate></asp:UpdatePanel></td><tdalign="left"style="width: 115px"><asp:TextBoxID="txtCommissioningID"runat="server"Width="115px"></asp:TextBox></td><tdalign="left"style="width: 75px"><asp:TextBoxID="txtAmount"runat="server"Width="75px"></asp:TextBox></td><tdalign="left"style="width: 75px"><asp:TextBoxID="txtRate"runat="server"Width="75px"></asp:TextBox></td><tdalign="left"style="width: 45px"><asp:ButtonID="btnAddOrDelete"runat="server"Text="Add"Width="45px"/></td></tr>

</

table>

-----------------------------

In my code behind of the ASCX control, I have a property that returns the TextBox located inside of the UpdatePanel:

-----------------------------

Public

ReadOnlyProperty ProducerID()As TextBoxGetReturn txtProducerIDEndGetEndProperty

-----------------------------

I then load the control at some point in my ASPX page:

-----------------------------

producerControl = Page.LoadControl("~/MCAProducerBasePercentControl.ascx")

-----------------------------

Then when I try to access the property and get the text box to add a handler dynamically it fails because it cannot see the Text Box:

-----------------------------

AddHandler

CType(producerControl, MCAProducerBasePercentControl).ProducerID.TextChanged,AddressOfMe.HandleExternalIDValidation

-----------------------------


As an update, I decided to try creating the TextBox control on the fly in the ASPX page, adding the Event Handler and the adding it to the Controls collection of the ContentTemplateContainer object inside of the UpdatePanel. For example:

CType

(producerControl, MCAProducerBasePercentControl).ProducerIDUpdatePanel.ContentTemplateContainer.Controls.Add(txtTest)When the page is rendered the event still does not fire off however I am seeing that it appears to have registered all of the update panels, inlcuding the one contained in my dynamically added ASCX control (highligted below in bold):

//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('ScriptManager1', document.getElementById('frmMCADetail'));
Sys.WebForms.PageRequestManager.getInstance()._updateControls(['tUpdatePanel2','tUpdatePanel1','tctl06$upProducerID'], [], [], 90);
//]]>

However, I also notice that the above reference does not match the actual ID of the panel:

(NOTE: a 't' has been added to all of the UpdatePanel ID names in the above PageRequestManager. I am referring to the '$' versus the underscore character)

<div id="ctl06_upProducerID">
<input name="ctl06$txtTest" type="text" onchange="javascript:setTimeout('__doPostBack(\'ctl06$txtTest\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="ctl06_txtTest" />
</div>

In my other UpdatePanels, the ID matches and everything works great. Here is an example:

<div id="UpdatePanel1">
<input name="txtContractAccount" type="text" onchange="javascript:setTimeout('__doPostBack(\'txtContractAccount\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="txtContractAccount" style="width:100px;" />
</div>

Is this perhaps my problem at least in terms of this approach of adding the TextBox on the fly and the event not firing off?


Just a guess: maybe you both forget to add the dynamically created user control to some container on the page? Page.LoadControl only is not enough! I re-created the sample on my workstation (in C#), and it works fine, assuming it's done like this:

ASCX code:
<%@. Control Language="C#" AutoEventWireup="true" CodeFile="CalendarWithTextBox.ascx.cs" Inherits="CalendarWithTextBox" %>
<%@. Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="asp" %>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="TxtDate" runat="server" Width="120px" ReadOnly="false" AutoPostBack="true"></asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="TxtDate" />
</Triggers>
</asp:UpdatePanel>


Code-behind of user control:
public partial class CalendarWithTextBox : System.Web.UI.UserControl
{
public string Date
{
get
{
return TxtDate.Text;
}
set
{
TxtDate.Text = value;
}
}
}

and finally, the code-behind of the page
private CalendarWithTextBox Calendar;

protected void Page_Init(object sender, EventArgs e)
{
Calendar = Page.LoadControl("CalendarWithTextBox.ascx") as CalendarWithTextBox;
form1.Controls.Add(Calendar);
}

protected void Page_Load(object sender, EventArgs e)
{
Calendar.Date = String.Format("{0:dd.MM.yyyy}", DateTime.Now);
}

User control is loaded in Page_Init with purpose, as only then it properly participates in page viewstate, and your controls are ready when handling postback events (Page_Load happens after your button click handlers, for example!)


Good thinking but of course I have added the control to the Page. It shows up just fine once it is rendered. The control is just dead...I believe it is related though to both techniques I mention above in my previous posts. Not only can I not see the control to add an event handler, when I add a control on the fly and add to the UpdatePanel the ID's are mismatched anyway.

You seem to be really stuck on this idea of Page_Init which I kind of understand but 1) I have never had issues with just firing off my routines in the Page_Load event and things working fine and 2) this is not an issue related to loading the ASCX control. This is an issue with using the Ajax UpdatePanel in a user control.

So I will ask again, is there a member of the MS team that can say whether or not definitively if Ajax can be used with a user control loaded using ASCX and Page.LoadControl()?

Thanks!

DK


There is nothing that forbids using update panel combined with dynamically loaded controls. Done that many times. Not without problems, there is always something new to discover about AJAX, but it does work.

Nevertheless, I've committed a small sample in VB, looking like your scenario (user control with update panel, loaded dynamically, with control whose events handlers are provided by the containing page). Here it just works! I hope this will be helpful. For some reasons I can't submit attachments, so I provide complete code down here in the post. Create a new empty AJAX website (VB), then copy'n'pastedefault.aspx andmycontrol.ascx files listed below.

And indeed, preaching the use of Page_Init has become a kind of a personal obsession, after seeing so many people getting into trouble because of ignoring the page event sequence ...

MyControl.ascx
<%@. Control Language="VB" AutoEventWireup="false" CodeFile="MyControl.ascx.vb" Inherits="MyControl" %>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="true" UpdateMode="Always">
<ContentTemplate>
Type some text:<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:Button ID="Button1" runat="server" Text="Ok" Width="65px" />
</ContentTemplate>
</asp:UpdatePanel>

MyControl.ascx.vb
Partial Class MyControl
Inherits System.Web.UI.UserControl

Public Property Text() As String
Get
Return TextBox1.Text
End Get
Set(ByVal value As String)
TextBox1.Text = value
End Set
End Property

Public ReadOnly Property OkButton() As Button
Get
Return Button1
End Get
End Property

End Class

Default.aspx
<%@. Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<%@. Register src="http://pics.10026.com/?src=MyControl.ascx" TagName="MyControl" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="panelControls" runat="server">
</asp:Panel>
<asp:Panel ID="panelResult" runat="server">
<asp:Label ID="LabelResult" runat="server" Text="-"></asp:Label><br />

</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>

Default.aspx.vb
Partial Class _Default
Inherits System.Web.UI.Page

Private control As MyControl

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
control = CType(Page.LoadControl("~/MyControl.ascx"), MyControl)
panelControls.Controls.Add(control)
AddHandler control.OkButton.Click, AddressOf Me.ButtonOk_Click
End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not Page.IsPostBack) Then
control.Text = "Hello"
End If
End Sub

Protected Sub ButtonOk_Click(ByVal sender As Object, ByVal e As System.EventArgs)
LabelResult.Text = "You've entered: " & control.Text
UpdatePanel.Update()
End Sub

End Class


Thanks much for the sample. I will follow your advice and try your sample project to see if I can get the same results. Perhaps it will show me something obvious I am missing.

On the Page_Init thing, I understand your sentiment and very much appreciate your effort. I really appreciate the help you have given me thus far.

DK


Well I think I finally got it working properly. I think your solution offered me a couple of insights.

First, I did have to add the dynamically loaded control to a Controls collection of some control on the page before I could add a handler. Perhaps that is what you were saying earlier but I took your post that you were asking if I was adding the ASCX control to the page at all. Anyway, once I added it to the Table's Control collection on my Page, I was able to access the TextBox and add a handler.

Secondly, your example made me realize that I was not rendering the controls again on a post back. I am not sure how I missed that one ;-) I have a need for controls to be dynamically loaded both on a selection from a dropdown and when someone clicks an Add button. I will need to place that added data in session somewhere and then load it each time so that when the partial page postback occurs it will add the handler again and everything will be wired up since these controls are not statically added to the page at design time and I don't have anything in Viewstate for them (unless I am missing something?).

I also decide to follow your advice on using Page_Init and it has prompted me to revisit the page life cycle text again to make sure I am up to speed.

I don't know if this thread is finished and I am not sure which post to mark as having the answer. Thanks again for your help and I will post if I have any updates.

DK


Nice to hear that, I hope you will get the remaining issues solved too.

As for adding controls - it indeed needs to be added to the ASP.NET form control, or somewhere within it's scope. Same in design time - if you place a control outside of <form> tag, you will also get a nasty runtime error.

If you create the user control in Page_Init and assign it with an explicit and always the same server-side ID, you do not need to preserve the drop down list items in a session or stuff. Just add the new items to DropDownList.Items collection whenever you need it, and they will be preserved in the viewstate and assigned back to your dropdown on postbacks. It does not make a difference if you make a control dynamically or design time - as long as you do it in a right sequence, they all can make use of the view state.

It seems that we've exhausted the issue, so feel free to close the thread any time!


Hi guys,

Just wanted to add my issue and what I discovered I had to do.

I'm dynamically loading a bunch of ascx controls into tables that are created by ascx controls.
Pseudocode

for each ctl in list of control definitions loaded from an xml file (or database)
create an ascx ctl (that has an update panel in it) with loadcontrol (this could be a control which would cause this loop to be executed for the controls in that control basically a panel with panels in it)
set some values
add to this control's table control.
loop

on post back, I get an error of cannot find ctl named ddValue for displayPanel trigger.
I think the problem occurs because the top ascx control isn't added to the main Page controls until after all the sub controls are added and when it gets to the postback control, it's trying to add it to a control that hasn't been added to the page yet. weird thing is it doesn't cause any problem when it loads the first time it's only on postback.

I fixed it by assigning the trigger in the code for the ascx load event instead of declaratively on the ascx page.