Showing posts with label postback. Show all posts
Showing posts with label postback. Show all posts

Wednesday, March 28, 2012

Ajax Beta 1, UpdatePanel and Viewstate issue

Hi all,

I have found what could be a possible bug in the beta 1 regarding the use of the UpdatePanel with postback events.

If we use the update panel and inside it there is a control like a linkbutton that raise a postback, then the event is generated on the server and everything is going on correctly.

In my scenario I have a base page class that overrides the Viewstate load and save methods to compress and decompress it.A simply code that work fine without ajax and with the atlas ctp.(the code put the compressed viewstate content in another hidden field and let the original __VIEWSTATE empty).

With beta1 I've found that with a viewstate compression, this cause the postback events not raised with the right postback value.This happens for example when we click for the second time to the link button, when the viewstate has to be regenerated from the previous click.

I don't know what happens but I think that something has changed in the way the beta1 and UpdatePanel look at the viewstate.

Anyone has had the same issue ?

I just had this problem occur to me this afternoon. Upgraded to the new beta 2 from Atlas and the controls inside my update panels that stored values in ViewState started behaving funny. I too was inheriting from a base class that compressed and cached ViewState. As soon as I took this out and went back to System.Web.UI.Page, the controls worked fine again. This really sucks as we were able to trim so much bloat out of the page by compressing the ViewState. It would be wonderful if MS would consider this.

Forza Milan!


Colt45, to get his scenario working, you would need to explicitly register the hidden field that stores the compressed value of viewstate with ScriptManager, so that the framework would know that it needs to send the updated value for this to the client during an async post-back. I am guessing that you currently use Page.ClientScript.RegisterHiddenField(...) to render your compressed view state. Change this to ScriptManager.RegisterHiddenField(...)

This should fix your issue.

Hope that helps!


Thank you very much, kashif

It works well now...


Sorry...my previous post was wrong...it doesn't work!

I' ve used the ScriptManager.RegisterHiddenField as you suggest but nothing changed.

I need a solution because the viewstate compression is a usefull feature that I don't want to give up, as like as I don't with Ajax...


It did not work for me either.

Most of the problems I see are occuring in GridViews with paging and/or sorting. For example, I have a sorting routine that sorts ASC the first time the header is clicked and then DESC if it is clicked again. The value is stored in ViewState. The first time I click the header, the columns sorts ASC as expected. At this point, "ASC" is stored in ViewState so that when the header is clicked again, I can check this value and then sort by the reverse ("DESC"). However, the grid sorts ASC with every click because the new value is not persisting.

Paging also causes problems. The page data will refresh on the screen correctly between pages 1, 2, 3 etc. However, if I click a button in the 3rd row on the 3rd page that is supposed to update that customer record, it will actually retrieve the customer record that is on the 3rd row of the 1st page. In other words, Ajax always thinks the grid is on the 1st page even though the data on the screen reflects the 3rd page.

If I turn off compressing/caching ViewState, it works fine.
If I leave compression/caching enabled, but turn of Ajax, it works fine.
But together, the marriage fails.


protected override void SavePageStateToPersistenceMedium(Object pViewState)
{
Pair pair1;
System.Web.UI.PageStatePersister pageStatePersister1 = this.PageStatePersister;
Object ViewState;
if (pViewState is Pair)
{
pair1 = ((Pair)pViewState);
pageStatePersister1.ControlState = pair1.First;
ViewState = pair1.Second;
}
else
{
ViewState = pViewState;
}

LosFormatter mFormat = new LosFormatter();
StringWriter mWriter = new StringWriter();

mFormat.Serialize(mWriter, ViewState);
String mViewStateStr = mWriter.ToString();

byte[] pBytes = System.Convert.FromBase64String(mViewStateStr);

pBytes = Compress(pBytes);

String vStateStr = System.Convert.ToBase64String(pBytes);

pageStatePersister1.ViewState = vStateStr;

pageStatePersister1.Save();

//ClientScript.RegisterHiddenField("__MSPVSTATE", vStateStr);

}

protected override Object LoadPageStateFromPersistenceMedium()
{
System.Web.UI.PageStatePersister pageStatePersister1 = this.PageStatePersister;
//try
//{
pageStatePersister1.Load();
//}
//catch
//{
// return null;
//}

String vState = pageStatePersister1.ViewState.ToString();

byte[] pBytes = System.Convert.FromBase64String(vState);

pBytes = DeCompress(pBytes);

LosFormatter mFormat = new LosFormatter();

Object ViewState = mFormat.Deserialize(System.Convert.ToBase64String(pBytes));

return new Pair(pageStatePersister1.ControlState, ViewState);
}


Using ScriptManager.RegisterHiddenField(...) works fine in Beta 2 as long as you set the first argument as an update panel. The update panel can be empty, and should have its UpdateMode set to Always. UsingFiddler you should be able to see your new viewstate hidden field change appropriately.

Whether this is any better or worse than the code in the previous post, I don't know.

Andy

1protected override object LoadPageStateFromPersistenceMedium()2{3string viewState = Request.Form["__VSTATE"];4byte[] bytes = Convert.FromBase64String(viewState);5bytes = Compressor.Decompress(bytes);6LosFormatter formatter =new LosFormatter();7return formatter.Deserialize(Convert.ToBase64String(bytes));8}9protected override void SavePageStateToPersistenceMedium(object viewState)10{11LosFormatter formatter =new LosFormatter();12StringWriter writer =new StringWriter();13formatter.Serialize(writer, viewState);14string viewStateString = writer.ToString();15byte[] bytes = Convert.FromBase64String(viewStateString);16bytes = Compressor.Compress(bytes);17ScriptManager.RegisterHiddenField(this.updVS,"__VSTATE", Convert.ToBase64String(bytes));18}

Hi,

I to am experiencing this problem, i'm using Ajax RC1. I would take the option to use the scriptmanager but i have 2 major problems with this solution, i have a master page that contains the scriptmanager, and i want to apply this to all my existing pages. How can i reference the scriptmanager on the master page from the base class? If at all possible?


Kind regards,

Pedro Costa


Useshunzimm solution above. A slightly modified version of it worked well for me. I have ScriptManager on my master page and it works fine.


This might perhaps be due to changes in the ajax framework, but I've found that you do not need a update panel for ScriptManager.RegisterHiddenField() to work. I just used this as the first param and everything seems okay so far.


Thanks for this post, fixed my issue too with using scriptmanager. One question I have is does it buy anything to have this viewstate compression code on top of IIS 6 HTTP Compression or does http compression make this code obselete?


I've been trying to use the compression code in my application and I'm finding that it's causing problems with a few gridviews that I'm using. What's happening is that the 'OnRowUpdating' and the 'OnRowCancelingEdit' events are not being fired. I have an 'update' and 'cancel' LinkButton inside an 'EditItemTemplate' tag in a 'TemplateField'. The 'OnRowEditing' and the 'OnRowDeleting' events are being fired, but not the other two. Do you have any idea why this might be happening? Any help would be greatly appreciated.

AJAX becomes full postback in IIS

I made a simple AJAX page in Visual Studio 2005, which has a button click to get server's system time. It works fine inside the VS2005. But when I put it on IIS in Windows Server 2003, the button click becomes a full postback. Do I miss something? Does anyone have any idea?I wrote a testing Ajax website to get server time in a asp:UpdatePanel and deplyed it to Windows Server 2003 IIS.It worked fine and didn't?happen?to full postback.Here are my sample codes for your reference.Wish this can give you some helps.
<div>
<asp:UpdatePanel ID="upnlServerTime" runat="server">
<ContentTemplate>
<asp:Label ID="lblServerTime" runat="server" Text="Server Time"></asp:Label>
<asp:Button ID="btnServerTime" runat="server" Text="Get Server Time" OnClick="btnServerTime_Click" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnServerTime" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
Behind Code:
protected void btnServerTime_Click(object sender, EventArgs e)
{
Label lblServerTime = upnlServerTime.FindControl("lblServerTime") as Label;
lblServerTime.Text = DateTime.Now.ToLongTimeString();
}


I doubt you don't create web application when you create a virtual directory in IIS.Right mouse click virtual directory in IIS and select Properties,Click "Create" button to create application name and Choose Execute Permission for "Scripts only" or "Scripts Executable" from permission DropDownList.Try to addNetwork Service to virtual directory?when?deploying?Ajax?
website.
Wish this can give you some ideas.

ajax based page need to go to the top of the page....

Hi everyone ,,,

i have a page that contain update panel , that uses partial rendering ..

i need to go to the top of the page after postBack ... how do i do this ?

thnx ..


Why would you want a postback if you are using Update PanelSmile

The Update Panel and other partial rendering sections are solely meant for avoiding the page from going to the top for each and every action and retainng the scroll position.

Is there a specific reason you want the page to scroll up?


i need it because i have a gridview at the bottom of the page that i select a row from it ,

and i get an information about the row at the top of the page , if i have a lot of rows when i select a row i stay on the position of the row and the info is not display for

the user, the user need to scroll to the top of the page ..



Use this Peace of Code:
-------------------------------
<!--Add the following after the scriptmanager on your page:-->

 <script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
window.scrollTo(0,0);
}
</script>

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

If that doesnt work for some reason, try this

Use HTML Bookmarks to achieve this without a Postback

1) Place HTML Bookmark <a name="top" >TOP</a> on Top of the Page

2) Use Response.Redirect("PageURL#top) to go to the top of the page

Read more about Bookmark on this:
http://www.freewebmasterhelp.com/tutorials/html-basics/4

Shrinand Vyas

Monday, March 26, 2012

Ajax Auto Postback I think needed

Alright I am attempting to make a site to do ping tests and I would like to make it look as realistic as the command prompt as possible. That is as far as having one result returned at a time.

currently it returns all of the pings responses all at once instead of one at a time. you can check out the code in working order at http://tools.shotdrive.com

here is my code behind page code

protected void DNSCheck_btn_Click(object sender, EventArgs e)
{
Timer1.Enabled = true;
}

protected void pingfunction()
{
try
{
//
switch (PingStatus)
{
case "Success":

lblStatus.Text += "Reply from: " + Convert.ToString(pingreply.Address) + " \r";
lblStatus.Text += "Bytes: " + Convert.ToString(pingreply.Buffer.Length.ToString()) + " \r ";
lblStatus.Text += "Time: " + Convert.ToString(pingreply.RoundtripTime) + " \r";
lblStatus.Text += "TTL: " + Convert.ToString(pingreply.Options.Ttl) + " \r <br>";

//ResponseText += "Reply from: " + Convert.ToString(pingreply.Address) + " \r";
//ResponseText += "Bytes: " + Convert.ToString(pingreply.Buffer.Length.ToString()) + " \r ";
//ResponseText += "Time: " + Convert.ToString(pingreply.RoundtripTime) + " \r";
//ResponseText += "TTL: " + Convert.ToString(pingreply.Options.Ttl) + " \r <br>";
break;

case "TimedOut":
lblStatus.Text += "Request timed out.<br>";

//lblStatus.DataBind();
break;

case "DestinationHostUnreachable":
lblStatus.Text += "Destination Host Unreachable<br>";
//lblStatus.DataBind();
break;

case "DestinationUnreachable":
lblStatus.Text += "Ping request could not find host r.red.com. Please check the name and try again.<br>";
//lblStatus.DataBind();
break;
case "BadDestination":
lblStatus.Text += "Ping request could not find host r.red.com. Please check the name and try again.<br>";
//lblStatus.DataBind();
break;

case "BadRoute":
lblStatus.Text += "Ping request could not find host " + txtHost.Text.Trim() + " Please check the name and try again <br>";
//lblStatus.DataBind();
break;

default:
lblStatus.Text = "SOME Error";
break;

}

}
catch (Exception err)
{

lblStatus.Text += "Ping request could not find host " + txtHost.Text.Trim() + " Please check the name and try again <br>";

}
}
protected void Timer1_Tick(object sender, EventArgs e)
{

lblStatus.Text = null;

for (int q = 0; q < Convert.ToInt32(tb_PingCount.Text); q++)
{
String host = txtHost.Text.Trim();
pingreply = ping.Send(host);
PingStatus = pingreply.Status.ToString();
pingfunction();

}
}

and my aspx page code

<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %
<%@dotnet.itags.org. Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %
<!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">
<div>

<asp:ScriptManager ID="ScriptManager1" runat="server" />

<div style="left: 134px; width: 895px; position: relative; top: 0px; height: 502px">

<asp:Button ID="DNSCheck_btn" runat="server" OnClick="DNSCheck_btn_Click" Style="left: 313px;
position: relative; top: -1px" Text="Submit" /><asp:TextBox ID="txtHost" runat="server" Style="left: -74px;
position: relative; top: -3px"></asp:TextBox><asp:RegularExpressionValidator
ID="RegularExpressionValidator1" runat="server" ControlToValidate="tb_PingCount"
ErrorMessage="Invalid Input" Style="left: 16px; position: relative; top: -4px"
ValidationExpression="^(.?\d*)$"></asp:RegularExpressionValidator><asp:TextBox ID="tb_PingCount" runat="server"
Style="left: -131px; position: relative; top: -2px" Width="39px">1</asp:TextBox><br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" RenderMode="Inline">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Enabled="False" Interval="5000" OnTick="Timer1_Tick">
</asp:Timer>

<div style="left: 0px; width: 417px; position: relative; top: 0px; height: 42px">
</div>

<asp:Label ID="lblStatus" runat="server" Height="185px"
Style="left: -14px; position: relative; top: 4px" Width="391px"></asp:Label>
<asp:Label ID="lbltest" runat="server" Style="left: 68px; position: relative; top: -12px"
Width="169px"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DNSCheck_btn" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<br />
</div>

</div>
</form>
</body>
</html>

Any Help on this would be greatly appreciated

Some logical chage to your code can do that for you!

1. Add a hidden field. Add following line within update panll contenttemplate

<asp:HiddenField runat=server ID="counter" />

2.Add folloing lines in DNSCheck_btn_Click function

counter.Value = tb_PingCount.Text;
lblStatus.Text = "";

3.Modify Timer1_Tick as follows

protected void Timer1_Tick(object sender, EventArgs e)
{

// lblStatus.Text = null;

//for (int q = 0; q < Convert.ToInt32(tb_PingCount.Text); q++)
//{
String host = txtHost.Text.Trim();
pingreply = ping.Send(host);
PingStatus = pingreply.Status.ToString();
pingfunction();
int count=Convert.ToInt32(counter.Value);
count=count-1;
counter.Value = count.ToString();
if (count == 0)
Timer1.Enabled = false;
//}
}

This should work. I hope you understood the logic.


Thank you that worked perfectly

Ajax asynchronous postback

Hi all,

I have created a web page with ajax support. In that i have two buttons and three textbox.

All the three textboxes having required field validator attached to them. Now while i am trying to do asynchronous postback it is not possible for me because the required field validator prompts me to enter values. Is there any way to get rid of this...

I would like to do asynchronous postback even though ther are validators on the page

Do u set the same value to propertie ValidationGroup for validators and the button that cause the validation?


 This will not cause validation :
 <asp:button ID="someButton"CausesValidation="false" runat="server" />

Hi SathishRaja,

My understanding of your issue is that you want to get rid of the validation when click the button which will normally fire the validators. If I have misunderstood, please feel free to let me know.

As far as I know, there are three methods to achieve this list below:

Solution 1


Thanks Solution 2 is Working fine for me.

AJAX Async postback

Hi

I have a WebForm in this web form i am dynamically loading 6 User Controls these user controls has ajax update panel. & these update panel have web controls.

Now when i click any control of any UCs that click is causing a page post back. due to this all my other cotrols are getting reloaded & respectibve UCs page load is getting fired. I want to restrict this.

I want to add condition on each UC's page load event to check whether this postback is caused due to some other UC's event. If it is caused due to some other UCs event then dont process anything. If it is caused due to its own event then only process it.

I need this cause i see the performnce impact of this.

Hi,

if you set UpdateMode rproperty for each UpdatePanel to "conditional" you can avoid updating all update panels on every click. You will also need to check that your ChildrenAsTriggers property is set to "true".

However, if you do some time consuming procesing on the server you will still need to check which control caused asyncpostback.

-yuriy
http://couldbedone.blogspot.com


Hey yuriy

Thanks for your response. Can you jsut tell me how can i check which control caused Asyncpostback...thats what am lookinh for.


Property of the ScriptManager: AsyncPostBackSourceElementID