ラベル update の投稿を表示しています。 すべての投稿を表示
ラベル update の投稿を表示しています。 すべての投稿を表示

2012年3月28日水曜日

Reset controls in update panel when error is thrown

Hello fellow developers,

A user enters a value in a textbox and i click a button to get some data, but a server error is thrown.

Is there a way to clear/reset the textbox in an UpdatePanel when there is a server error?

If there is a way, can someone assist in providing me that trick?

Thanks in Advance.

Protected Sub myButton_Click(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles myButton.Click
Try
' Whatever code that I'm trying to run goes here.
' This is the code that my produce the error.
Catch
myTextbox.Text =""
End Try
End Sub


Can't you simply use a try/catch block, and catch the exception? If an exception is thrown reset it to the old value. You can use a hidden label or textbox to store the previous value.


Use this

protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
{
if (condition)
{
ScriptManager1.AsyncPostBackErrorMessage =
e.Exception.Message;

}
else
{
ScriptManager1.AsyncPostBackErrorMessage =
"An unspecified error occurred.";
}
}


I apologize. My example scenario was not explained the way I originally thought.

The example should be that when using AJAX you want to show an error message AND reset the controls.

If you write code to 'Throw' a custom error message to an alert window, nothing after the 'Throw' gets executed (clearing my textbox).

So my question really should be:

Is there a way, using AJAX, to 'Throw' a custom error message to an alert window and still reset controls? Either on the server or client side.

Thanks.


Protected Sub myButton_Click(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles myButton.Click
Try
' Whatever code that I'm trying to run goes here.
' This is the code that my produce the error.
Catch exAs Exception
ScriptManager.RegisterStartupScript(Page, Page.GetType,"ErrorMsg", "alert('" & ex.Message & "');",True)
myTextbox.Text =""
End Try
End Sub


Thanks Buddha, that's just what I needed.

Resized image wont show in UpdatePanel

Hello,

I have a problem with a code where I want to resize an image in a Update Panel but when I fire up my site, I get this error in a message box:

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 '???JFIF'.

This is the code of the aspx page where the subs are called to resize and show the image (The formview is in a UpdatePanel):

1 <asp:FormView ID="DetailsFormView" runat="server" DataSourceID="DetailsFormSource">
2 <ItemTemplate>
3 <table style="vertical-align: top; text-align: left; width: 100%;">
4 <tr>
5 <td style="width: 150px; font-weight: bold;">
6 Initials:</td>
7 <td style="width: 278px">
8 <asp:Label ID="InitialerLabel" runat="server" Text='<%# Bind("Initialer")%>'></asp:Label></td>
9 <td rowspan="14" style="width: 188px">
10<%
11 ' make sure Nothing has gone to the client
12 Response.Clear()
13
14
15 If SearchGridView.SelectedValue = "" Then
16
17 Call sendError()
18
19 Else
20 If File.Exists(Server.MapPath("images/foto/" & SearchGridView.SelectedValue & ".jpg")) Then
21 Call sendFile()
22 Else
23 Call sendError()
24 End If
25
26 End If
27
28 Response.End()
29%>30 <asp:Image ID="EmpImg" runat="server" />
31 </td>
32 </tr>
33 <tr>
34 <td style="width: 150px; font-weight: bold;">
35 Full Name:</td>
36 <td style="width: 278px">
37 <asp:Label ID="FornavnLabel" runat="server" Text='<%# Bind("Fornavn")%>'></asp:Label>
38 <asp:Label ID="EfternavnLabel" runat="server" Text='<%# Bind("Efternavn")%>'></asp:Label></td>
39 </tr>
40 <tr>
41 <td style="width: 150px; font-weight: bold;">
42 Employee Nr.:
43 </td>
44 <td style="width: 278px">
45 <asp:Label ID="MedarbnrLabel" runat="server" Text='<%# Bind("Medarbnr")%>'></asp:Label></td>
46 </tr>
47 <tr>
48 <td style="width: 150px; font-weight: bold;">
49 Department code:</td>
50 <td style="width: 278px">
51 <asp:Label ID="afdelingskodeLabel" runat="server" Text='<%# Bind("afdelingskode")%>'>
52 </asp:Label></td>
53 </tr>
54 <tr>
55 <td style="width: 150px; font-weight: bold;">
56 Private address:</td>
57 <td style="width: 278px">
58 <asp:Label ID="padresseLabel" runat="server" Text='<%# Bind("padresse")%>'></asp:Label>,
59 <asp:Label ID="ppostnrLabel" runat="server" Text='<%# Bind("ppostnr")%>'></asp:Label>
60 <asp:Label ID="Bynavn" runat="server" Text='<%# Bind("Bynavn")%>'></asp:Label></td>
61 </tr>
62 <tr>
63 <td style="width: 150px; font-weight: bold;">
64 Private phone:</td>
65 <td style="width: 278px">
66 <asp:Label ID="ptelefonLabel" runat="server" Text='<%# Bind("ptelefon")%>'></asp:Label></td>
67 </tr>
68 <tr>
69 <td style="width: 150px; font-weight: bold;">
70 Private cellphone:</td>
71 <td style="width: 278px">
72 <asp:Label ID="pmobilLabel" runat="server" Text='<%# Bind("pmobil")%>'></asp:Label></td>
73 </tr>
74 <tr>
75 <td style="width: 150px; font-weight: bold;">
76 Phone:</td>
77 <td style="width: 278px">
78 <asp:Label ID="telefonLabel" runat="server" Text='<%# Bind("telefon")%>'></asp:Label></td>
79 </tr>
80 <tr>
81 <td style="width: 150px; font-weight: bold;">
82 Cellphone / Shortnr:</td>
83 <td style="width: 278px">
84 <asp:Label ID="mobil1Label" runat="server" Text='<%# Bind("mobil1")%>'></asp:Label>
85 /
86 <asp:Label ID="mobil2Label" runat="server" Text='<%# Bind("mobil2")%>'></asp:Label></td>
87 </tr>
88 <tr>
89 <td style="width: 150px; font-weight: bold;">
90 Mail address:
91 </td>
92 <td style="width: 278px">
93 <asp:Label ID="mailLabel" runat="server" Text='<%# Bind("mail")%>'></asp:Label>@dotnet.itags.org.***.com</td>
94 </tr>
95 <tr>
96 <td style="width: 150px; font-weight: bold;">
97 Private mail:</td>
98 <td style="width: 278px">
99 <asp:Label ID="pmailLabel" runat="server" Text='<%# Bind("pmail")%>'></asp:Label></td>
100 </tr>
101 <tr>
102 <td style="width: 150px; font-weight: bold;">
103 Based:
104 </td>
105 <td style="width: 278px">
106 <asp:Label ID="hjemh?rendeLabel" runat="server" Text='<%# Bind("hjemh?rende")%>'>
107 </asp:Label></td>
108 </tr>
109 <tr>
110 <td style="width: 150px; font-weight: bold;">
111 Position:</td>
112 <td style="width: 278px">
113 <asp:Label ID="StillingLabel" runat="server" Text='<%# Bind("Stilling")%>'></asp:Label></td>
114 </tr>
115 <tr>
116 <td style="width: 150px; font-weight: bold;">
117 Vehicle nr.:</td>
118 <td style="width: 278px">
119 <asp:Label ID="vognnrLabel" runat="server" Text='<%# Bind("vognnr")%>'></asp:Label></td>
120 </tr>
121 </table>
122 </ItemTemplate>
123 </asp:FormView>
124

And this are the subs that is resizing the image:

 
1Function NewthumbSize(ByVal currentwidth,ByVal currentheight)
234' Calculate the Size of the New image56Dim tempMultiplierAs Double
78 If currentheight > currentwidthThen' portrait9 tempMultiplier = 200 / currentheight
10Else11 tempMultiplier = 200 / currentwidth
12End If
131415 Dim NewSizeAs New Size(CInt(currentwidth * tempMultiplier),CInt(currentheight * tempMultiplier))
1617Return NewSize
18End Function
192021 Public Sub sendFile()
2223' create New image and bitmap objects. Load the image file and put into a resized bitmap.24Dim gAs System.Drawing.Image = System.Drawing.Image.FromFile(Server.MapPath("images/foto/" & SearchGridView.SelectedValue &".jpg"))
25Dim thisFormat = g.RawFormat
2627Dim thumbSizeAs New Size
28 thumbSize = NewthumbSize(g.Width, g.Height)
2930Dim imgOutputAs New Bitmap(g, thumbSize.Width, thumbSize.Height)
3132' Set the contenttype3334 Response.ContentType ="image/jpeg"353637 imgOutput.Save(Response.OutputStream, thisFormat)' output to the user
3839 ' tidy up40 g.Dispose()
41 imgOutput.Dispose()
4243End Sub
4445 Public Sub sendError()
4647' if no height, width, src then output "error"48Dim imgOutputAs New Bitmap(120, 120, PixelFormat.Format24bppRgb)
49Dim gAs Graphics = Graphics.FromImage(imgOutput)' create a New graphic object from the above bmp50 g.Clear(Color.Yellow)' blank the image51 g.DrawString("ERROR!",New Font("verdana", 14, FontStyle.Bold), SystemBrushes.WindowText,New PointF(2, 2))
52' Set the contenttype53 Response.ContentType ="image/gif"5455' send the resized image to the viewer56 imgOutput.Save(Response.OutputStream, ImageFormat.Gif)' output to the user
5758 ' tidy up59 g.Dispose()
60 imgOutput.Dispose()
61End Sub

I search a bit on the the what the problem could be, and I didn't find enything than that Response.Write can't be used, but I didn't hear nothing about the others Response methods that I am using.

You can't inject that type of data into the response stream of a partial postback. It boils down to the exact same problem as using Response.Write.

If I were you, I'd change that to a regular image control with the ImageURL dynamically assigned through code similar to what you have. If the thumbnail already exists, your function can return the path/file to it. If not, it creates the thumbnail and then returns the path/file. If there's an error, it can return the path/file of that error GIF.


Hmm.. I thought about your idea but I don't want to have the images two times.

But I got the problem solved.

I made an file called Thumbnail.aspx and in it I wrote:

<%@. Page Language="VB" AutoEventWireup="false" CodeFile="Thumbnail.aspx.vb" Inherits="Thumbnail" ContentType="image/jpeg" %>

And in Tumbmail.aspx.vb I added this code:

Imports System
Imports System.IO
Imports System.Drawing
Imports System.Drawing.Imaging
PartialClass Thumbnail
Inherits System.Web.UI.Page

Private PathToImageAs String ="images/foto/"Sub sendFile()
' create New image and bitmap objects. Load the image file and put into a resized bitmap.Dim gAs System.Drawing.Image = System.Drawing.Image.FromFile(Server.MapPath(PathToImage & Request("src")))
Dim thisFormat = g.RawFormat
Dim imgOutputAs New Bitmap(g, 177, 239)

' Set the contenttype Response.ContentType ="image/jpeg"' send the resized image to the viewer imgOutput.Save(Response.OutputStream, thisFormat)' output to the user

' tidy up g.Dispose() imgOutput.Dispose()End Sub

Sub sendError()

' create New image and bitmap objects. Load the image file and put into a resized bitmap.Dim gAs System.Drawing.Image = System.Drawing.Image.FromFile(Server.MapPath("images/noimage.jpg"))
Dim thisFormat = g.RawFormat
Dim imgOutputAs New Bitmap(g, 177, 239)

' Set the contenttype Response.ContentType ="image/jpeg"' send the resized image to the viewer imgOutput.Save(Response.OutputStream, thisFormat)' output to the user

' tidy up g.Dispose() imgOutput.Dispose()End Sub

Protected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.Load

' make sure Nothing has gone to the client Response.clear()If Request("src") ="" Then
Call sendError()

Else

If File.Exists(Server.MapPath("PathToImage & Request("src")))Then
Call sendFile()
Else
Call sendError()
End If

End If response.end()End Sub
End Class

And in my formview I added this to display the image:

<img src="http://pics.10026.com/?src=Thumbnail.aspx?src=<%# SearchGridView.SelectedValue %>.jpg" alt="" style="border: 0px" />

That works for me,

Resortlist doesnt update datasource

Hi,

I have a problem with resortlist that makes me mad :-)

I want to bind an ObjectDataSource or a SQLDataSource to a reorderlist, which both works fine when loading data into a itemlist. I can drag and drop all items - but whatever I do, the changed position of my list items won't be saved, neither to the ODS nor the SQLDatasource. Btw: Actually I use the Control Toolkit released mid December and AJAX RC 1. Any idea what's going wrong?


1 <asp:SqlDataSource ID="SQLDataSource1" runat="server"2 ConnectionString="(...)"3 SelectCommand="SELECT [ID], [Name1], [Name2], [order] FROM [tbl_orderlist]"4 UpdateCommand="UPDATE [tbl_orderlist] SET [order]=@dotnet.itags.org.order WHERE [ID]=@dotnet.itags.org.ID">5 <UpdateParameters>6 <asp:Parameter Name="ID" Type=int32 />7 <asp:Parameter Name="order" Type="int32" />8 </UpdateParameters>9 </asp:SqlDataSource>1011 <ajaxToolkit:ReorderList ID="ReorderList1" runat="server"12 DataSourceID="SQLDataSource1"13 ShowInsertItem="true"14 LayoutType="Table"15 DragHandleAlignment="Left"16 DataKeyField="ID"17 AllowReorder="true"18 SortOrderField="order"19 PostBackOnReorder="true"20 CssClass="keyword" >2122 <DragHandleTemplate>23 <div class="dragHandle">24 <table border="0" cellspacing="0" cellpadding="0">25 <tr>26 <td valign="top" class="moveitem"><asp:Label ID="Label1" runat="server" Text='<%# Eval("Name1")%>' /></td>27 <td valign="top" class="moveitem"><asp:Label ID="Label2" runat="server" Text='<%# Eval("Name2")%>' /></td>28 </tr>29 </table>30 </div>31 </DragHandleTemplate>32 </ajaxToolkit:ReorderList>

Thanx a lot for every hint!Smile

Join the club...

I'm fighting the same battle, and it's driving me nuts! The update command simply refuses to fire. I had it working, and now it doesn't work. I just can't seem to get the event to fire.

What happens when you set PostBackOnReorder="false"?


I'm experiencing the same problem! And have no idea what to do... Could anyone from Microsoft Team comment this situation?

Any ideas??


Same problem here!!!! It seems like a bug inside the Reorderlist. Any help here?

Try this site:http://www.codeplex.com/AtlasControlToolkit

In my case, I put a TextBox inside <EditItemTemplate> and binded it to the column in the DB that needs to be updated when reordering:

<EditItemTemplate> <asp:TextBox ID="txtItemOrder" runat="server" Text='<%# Bind("ItemOrder")%>' /></EditItemTemplate>

has anyone figured this out yet?!?!? and does anyone know where I can download the actual code from the AJAX sample website so I can have a look at how MS implemented this?
Driving me crazy!!!


Could you please post the code that actually handles the updateproces for you? So the code-behind method and your datasource/reorderlist definition?

Thanks ahead!


I basically just copied the actual code from the AJAX sample website and tweaked that. I also didn't use any code-behind to handle the reordering. Here's the code:

1<asp:UpdatePanel ID="up1" runat="server">2 <ContentTemplate>3 <div class="reorderListDemo">4 <ajaxToolkit:ReorderList ID="ReorderList1" runat="server" Width="780px" PostBackOnReorder="true"5 DataSourceID="ReorderDataSource" CallbackCssStyle="callbackStyle" DragHandleAlignment="Left"6 ItemInsertLocation="Beginning" DataKeyField="Item_ID" SortOrderField="ItemOrder" CssClass="reorderList">7 <ItemTemplate>8 <div class="itemArea">9 <asp:Label ID="lblItemOrder" runat="server" Text='<%# HttpUtility.HtmlEncode(Convert.ToString(Eval("ItemOrder")))%>' />10 <asp:Label ID="lblName1" runat="server" Text='<%# HttpUtility.HtmlEncode(Convert.ToString(Eval("Name1", " - {0}")))%>' />11 <asp:Label ID="lblName2" runat="server" Text='<%# HttpUtility.HtmlEncode(Convert.ToString(Eval("Name2", " - {0}")))%>' />12 </div>13 </ItemTemplate>14 <EditItemTemplate>15 <div class="itemArea">16 <asp:TextBox ID="txtItemOrder" runat="server" Text='<%# Bind("ItemOrder")%>' ValidationGroup="edit" />17 </div>18 </EditItemTemplate>19 <ReorderTemplate>20 <asp:Panel ID="Panel2" runat="server" CssClass="reorderCue" />21 </ReorderTemplate>22 <DragHandleTemplate>23 <div class="dragHandle"></div>24 </DragHandleTemplate>25 </ajaxToolkit:ReorderList>26 </div>27 </ContentTemplate>28</asp:UpdatePanel>2930<asp:SqlDataSource ID="ReorderDataSource" runat="server" ConnectionString="<%$ ...%>"31 SelectCommand="SELECT [Item_ID], [Name1], [Name2], [ItemOrder] FROM [Table1]"32 UpdateCommand="UPDATE [Table1] SET [ItemOrder]=@.ItemOrder WHERE Item_ID=@.Item_ID">33 <UpdateParameters>34 <asp:Parameter Name="ItemOrder" Type="Int32" />35 </UpdateParameters>36</asp:SqlDataSource>37

hmm..in your updatecommand you use the parameter @.item_ID...wherefrom is this retreived?

Also, when you reorder items shouldnt there always be 2 items updated? if item 1 goes to index 2, item 2 should go to index 1 right? I dont see how that happens here...

Help is appreciated!

Ok, I now have this, but its still not working...what am I missing here?

<cc1:ReorderList PostBackOnReorder="true"
SortOrderField="RuleIndex"
ID="rolRules"
AllowReorder="true"
DataKeyField="RuleID"
DataSourceID="ReorderDataSource"
runat="server">
<ItemTemplate>
<%#Eval("RuleIndex")%>
<%#Eval("RuleName")%>
</ItemTemplate>
</cc1:ReorderList>

<asp:SqlDataSource ID="ReorderDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:SQLAuth %>"
SelectCommand="SELECT RuleID,RuleName,ruleindex FROM myRules WHERE UserCode=@.UserCode"
UpdateCommand="UPDATE myRules SET RuleIndex=@.RuleIndex WHERE RuleID=@.RuleID">
<SelectParameters>
<asp:QueryStringParameter QueryStringField="id" Name="UserCode" Type="int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="RuleIndex" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>


myRules table structure:
RuleID int
RuleName nvarchar(20)
ruleindex tinyint
<and some other fields
Thanks!


Peter Smith:

hmm..in your updatecommand you use the parameter @.item_ID...wherefrom is this retreived?

That Item_ID is referenced by the DataKeyField property of the ReorderList (similar with GridView), retrieved from the SELECT command in the DataSource.

Peter Smith:

Also, when you reorder items shouldnt there always be 2 items updated? if item 1 goes to index 2, item 2 should go to index 1 right? I dont see how that happens here...

Help is appreciated!

Well, I guess that's the beauty of the ReorderList control - it does the dirty work for us. As long as we declare which field from the SELECT command is the identity column, and the field that needs resorting... the control handles the rest. We'd have to look at the source code of ReorderList control in order to truly understand the inner workings of how it keeps track of which index should go to another index (etc).Smile But my guess is that, this is done using ViewState to "remember" the values (Identity column, and ItemOrder), and through Javascript's mouse event handlers which triggers the saving of the values to executing the UPDATE command in the DataSource. This is just my personal idea.

I am using AJAX Control Toolkit release 10301 (2007-03-01) and it worked for me using the code I posted here.(Quick note: I experimented with ReorderList again, and found out that using <EditItemTemplate> is not necessary to make the reordering mechanism work; so what I initially said in my first post in this thread doesn't apply anymore).

Best regards!


Peter Smith:

Ok, I now have this, but its still not working...what am I missing here?

Peter,

at first glance, your code looks fine. However, what caught my attention is the "cc1:" tag prefix for the ReorderList control. If the latest version of the AJAX Control Toolkit is correctly installed and registered, the tag prefix should normally be "ajaxToolkit:". So, you might first verify your correct installation of the CT.


che_rish:


Peter Smith:

Also, when you reorder items shouldnt there always be 2 items updated? if item 1 goes to index 2, item 2 should go to index 1 right? I dont see how that happens here...

Well, I guess that's the beauty of the ReorderList control - it does the dirty work for us. As long as we declare which field from the SELECT command is the identity column, and the field that needs resorting... the control handles the rest.

Just in addition to che_rish's excellent explanation: Note that it's not just about swappingtwo ItemOrder values... :) Actually, dragging an item to a different position can comprise as much as updating the ItemOrder fields ofevery single row in the list (for example, when dragging the last item to the first position. And yes, it's all done in the client-side JavaScript that comes with the ReorderList control.Smile


I also used same coding like u. I am also facing same problem.. If any resolves this just let me know.. Thank U.

2012年3月26日月曜日

Response.redirect causes post back using Atlas


Hi,

I have a webpage with a button on it. The button is placed in an update panel. I want to redirect user to another page when the user press the button. Basically it is a save button which save user information and redirect user to another page.

I tried using response.redirect("anotherpage.aspx") but it caused post back however the button is placed under a n update panel.

Can anyone help me out? I want to save data on button click and redirect user to another page without causing post back.


Thanks.
Imtiaz

Redirect has to cause a postback, you are trying to "redirect" the user.

Firstly, all things inside an update panel cause a postback, they just go through some different steps, and only deal with events in the update panel, and only refresh the part of the page inside the panel.

So your button is designed to postback, which it does... then redirects, the update panel picks this up, and changes the browser page.

The functionality is correct.

If you want, instead of a button with a redirect, make a regular html button with a clientside event.

onclick="redirect();"

function redirect(){

location.herf = 'newURL.aspx';

}

If you call a client side method to change the location of the page, then there is no post back to the server

Response.Redirect doesnt work with UpdatePanel in Beta 1

I have a page with an update panel that contains a few buttons that need to be able to redirect to another page. The script manager is located on a master page.

Every time one of those buttons are clicked, i get one of two errors:

    If the button is inside of a gridview, i get this error:
    Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed.
    If the button is NOT inside of a gridview, i get this error:
    Sys.WebForms.PageRequestManagerParserErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 302

Here's a test aspx page that I set up:

1<%@dotnet.itags.org. Page Language="VB" title="Untitled Page" MasterPageFile="~/main.master" AutoEventWireup="false" CodeFile="test.aspx.vb" Inherits="test" %>2<%@dotnet.itags.org. Register Assembly="Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="Microsoft.Web.UI" TagPrefix="ajax" %>3<asp:Content ID="Content1" ContentPlaceHolderID="plhContent" Runat="Server">4 <ajax:UpdatePanel runat="server">5 <ContentTemplate>6 <asp:Label runat="server" ID="lblTime" /><br />7 <asp:Button runat="server" ID="btnRefresh" Text="Refresh" /><br />8 <asp:Button runat="server" ID="btnRedirect" Text="Redirect" /><br />9 <asp:LinkButton runat="server" ID="lnkRedirect" Text="ASP Linkbutton" /><br />10 <a href="http://www.google.com/" title="test redirect">HTML Hyperlink</a>11 </ContentTemplate>12 </ajax:UpdatePanel>13</asp:Content>
And here's the codebehind:
1PartialClass test2Inherits System.Web.UI.Page34Protected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.Load5 lbltime.Text = now()6End Sub78 Protected Sub btnRedirect_Click(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles btnRedirect.Click9 Response.Redirect("http://www.google.com/",True)10End Sub1112 Protected Sub btnRefresh_Click(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles btnRefresh.Click13 lblTime.Text = Now()14End Sub1516 Protected Sub lnkRedirect_Click(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles lnkRedirect.Click17 Response.Redirect("http://www.google.com/",True)18End Sub19End Class


The LinkButton causes the same error, so it's not just limited to the button control. It looks like it affect anything that posts back to the server and causes a redirect.

Thanks for any help you can give me!

We found this out today too. The fix is to pass a location.href back to user.

ScriptManager.RegisterStartupScript(pnlYourUpdatePanel,this.GetType(),"redirectMe","location.href='blah.aspx';",true);

Sorry it is in C#... Hope this helps.


hello.

i've just built a sample project with the following code:

master page:

<%@. Master Language="VB" %
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<script runat="server"
</script
<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 runat="server" ID="manager" />
<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
</asp:contentplaceholder>
</div>
</form>
</body>
</html>

page:

<%@. Page Language="VB" MasterPageFile="~/MasterPage.master" Title="Untitled Page" %>
<script runat="Server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
lblTime.Text = Now()
End Sub

Protected Sub btnRedirect_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRedirect.Click
Response.Redirect("http://www.google.com/", True)
End Sub

Protected Sub btnRefresh_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
lblTime.Text = Now()
End Sub

Protected Sub lnkRedirect_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkRedirect.Click
Response.Redirect("http://www.google.com/", True)
End Sub
</script>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:updatePanel runat="server" id="panel">
<contenttemplate>
<asp:Label runat="server" ID="lblTime" /><br />
<asp:Button runat="server" ID="btnRefresh" Text="Refresh" /><br />
<asp:Button runat="server" ID="btnRedirect" Text="Redirect" /><br />
<asp:LinkButton runat="server" ID="lnkRedirect" Text="ASP Linkbutton" /><br />
<a href="http://links.10026.com/?link=http://www.google.com/" title="test redirect">HTML Hyperlink</a>
</contenttemplate>
</asp:updatePanel>
</asp:Content
everything is working here with the beta extensions. are you sure you've set up web.config correctly?


Luis,

When looking at the XMLHttpResponse google.com is being returned which is causing the parser error. Not sure how you are getting this to work with the Beta release?? Also, not sure how config would cause this?

Matt


hello.

well just recalled one problem i've seen before where the users updated the prefix but left it pointing to the old ctp dll which was still in the bin folder and it just blow everything apart. btw, here's what i'm getting back from the server side in response to a click over the redirect button (2nd one from the top):


22|pageRedirect||http://www.google.com/|


Luis Abreu:

everything is working here with the beta extensions. are you sure you've set up web.config correctly?

I think I do. I have a Microsoft.Web.Extensions assembly in the web.config. Is there aything else I need?

1<compilation debug="true" strict="false" explicit="true">2 <assemblies>3 <add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>4 <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>5 <add assembly="Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>6 </assemblies>7</compilation>


Luis Abreu:

well just recalled one problem i've seen before where the users updated the prefix but left it pointing to the old ctp dll which was still in the bin folder and it just blow everything apart.

I did delete the old CTP DLL, and added the new assembly registration to the top of the page:

1<%@. Register Assembly="Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="Microsoft.Web.UI" TagPrefix="ajax" %>2

hello again.

can you confirm the response you're getting back from the server? is it similar to the one i've shown before?


How do I access the server response information?

hello.

use fiddler. if you're using ie, you must create a site in IIS and then use the name of the machine (http://machinename/site). if you're using firefox, configure it so that it uses a local proxy (127.0.0.1 port 8888 if i'm not mistaken).


It is definitely in the config. Again... good call Luis... you are missing these values in your config and this should cure the problem.

<httpModules><add name="WebResourceCompression" type="Microsoft.Web.Handlers.WebResourceCompressionModule, Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/><add name="ScriptModule" type="Microsoft.Web.UI.ScriptModule, Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/></httpModules>
Thank Luis for that one. =)
P.S. That is under httpHandlers

That worked! You guys are awesome.


Thanks!


Thanks - Guys!

I was experiencing the same problem in Beta 2, which this solution apparently resolved that issue.


Hi Guys!

I Got the Same error in my current project. I cant redirect to another page from inside the UpdatePanel. Finally I saw this forum and got a wonder result and answer. Its really amazing and thanks a lot for u all guys..

rgds,

Senthil

Response.Redirect from UpdatePanel causes full refresh

I noticed that when I redirect to another page from within an update panel, the page fully refreshes (may be that's by design?).

How can I prevent this from happening?

Thanks.

you can not prevent this, this is the way any web sites works. When you say response.redirect, you are instructing the browser to make a fresh call to particular aspx page.


rmaiya:

you can not prevent this, this is the way any web sites works. When you say response.redirect, you are instructing the browser to make a fresh call to particular aspx page.

that is right.

If you are trying to only update the panel then try something like, updatePanel1.update();, or if you want to load a new page inside the panel try putting an iframe inside the panel


What is considered as best practice?

For example, if you click on the above links (such as "Learn", "Downloads", "Ajax"...) on this page, how do they ensure that that the header and footer elements of the page don't "blink"?


As they are different pages, I do want to do a response.redirect to keep the URL's friendly, but at the same time, I would like my header and other static elements not refresh each time. Do they use partial page caching to achieve this?

Response.Redirect in AJAX

I have a button in Update panel.

On button click I have written

Response.Redirect("InterMediateMsg.aspx", False)

When I executes the application I got the Error..

Sys.WebForms.PageRequestParserErrorException:The message received from the server could not be parsed.

How should I implement Redirection in AJAX.

Hi,

in the onclick (client side!!) you just place self.location.href='urltogoto'. Don't use AJAX for something like that but plain old javascript.

Grz, Kris.


Response.Redirect should work fine during an async postback. Try dropping the "False"... I'm not sure if you can use that option.


Actually I have performed server side coding( Database operations) on button click .

After the successful operation I want to navigate to another page.

How could I do it.


I have tried it by dropping false.

Actually this second parameter specifies whether I want to terminate execution of current page or not.

Is there any effect of browser.

I am using IE 6.0


Make sure that you have buffer set to false on the page from which you wish to redirect - otherwise output will already have been streamed out to the client, and things will go horribly wrong!

This cost me quite a bit of investigation a while ago..!


i think this error may be because it is trying to process a redirect within the update panel. assuming you use a trigger for the updatepanel and button, set it to a asp:PostBackTrigger instead of a asp:AsyncPostBackTrigger, this will send your page into a full postback, which may solve your problem (i haven't tested it).


I try the way you suggest, and its work !Wink


glad to help!Smile


Thnx ChrisCicc ,

It's working.

I have set the Trigger for button to PostBack and it worked.

Response.Redirect not working while inside an Update Panel

I have a link button inside an update panel. When the user clicks this button, it calls a function that performs a database update and then redirects them to another page. However, Response.Redirect isn't working with AJAX. Any suggestions how I can do this? Thanks!Can you post your code here?

Hi,

Reponse.Redirect works with UpdatePanel. Please refer to this sample:

<%@. Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"> protected void Button1_Click(object sender, EventArgs e) { Response.Redirect("http://www.microsoft.com"); }</script><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"> </asp:ScriptManager> </div> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> </ContentTemplate> </asp:UpdatePanel> </form></body></html>

Response.write in Update Panel

Is it possible to use a response.write in an update panel? I have a button converting a datagrid to excel using response.write. The button will work fine outside of the update panel but when I try it inside the update panel I am getting an error.

Try a response.clear

 Response.Clear() Response.AddHeader("content-disposition","attachment; filename=Survey_Results.xls") Response.Charset ="" Response.Cache.SetCacheability(HttpCacheability.NoCache)Dim stringWriterAs System.IO.StringWriter =New System.IO.StringWriter()Dim htmlWriteAs System.Web.UI.HtmlTextWriter =New HtmlTextWriter(stringWriter) stringWriter.Write("Question,Option,Option Type,Is Correct?,UserID" & vbCrLf)Dim colSurveyResultInfoAs List(Of SurveyResultInfo) = SurveyOptionController.GetSurveyResultData(ModuleId)Dim objSurveyResultInfoAs SurveyResultInfoFor Each objSurveyResultInfoIn colSurveyResultInfo stringWriter.Write(objSurveyResultInfo.Question &"," & objSurveyResultInfo.OptionName &"," & objSurveyResultInfo.OptionType &"," & objSurveyResultInfo.IsCorrect &"," & objSurveyResultInfo.UserId & vbCrLf)Next Response.Write(stringWriter.ToString()) Response.Flush() Response.Close()

After a little more research I found the answer.

<Triggers>
<asp:PostBackTrigger ControlID="btnExport" />
</Triggers>

http://ajax.asp.net/docs/mref/T_System_Web_UI_PostBackTrigger.aspx


You can't send a traditional octet stream file response in a partial postback because there isn't an HTTP response coming back to the browser. It's just a string returned to the XmlHTTPRequest.

However, you canuse an iframe to accomplish asynchronous file downloads.

Response.Write inside Updatepanel Beta 2

Hi,

I have a button inside a updatepanel, when the client click the button he can download a PDF. Everything works perfectly outside the update panel but not inside it. I got the next error message:

Sys.Webforms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error is when the response is modified by calls to Response.Write...

I really appreciate any help.

Thanks,

Jaime

My code:

PrivateSub ShowPdf(ByVal strPathAsString)

Response.ContentType =

"application/x-download"

Response.AddHeader(

"Content-Disposition","filename=YourPdf.pdf")

Response.WriteFile(strPath)

Response.End()

End Sub

<%@dotnet.itags.org.PageLanguage="VB"AutoEventWireup="false"CodeFile="Resultados.aspx.vb"Inherits="Resultados" %>

<%@dotnet.itags.org.RegisterAssembly="Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

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

<%

@dotnet.itags.org.RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"TagPrefix="AjaxToolKit" %>

<!

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">

.............

<

asp:UpdatePanelID="UpdatePanel1"runat="server"><ContentTemplate><tablestyle="width: 840px"><tr><tdstyle="width: 762px; height: 153px;"><AjaxToolKit:RoundedCornersExtenderID="RoundedCornersExtender1"runat="server"TargetControlID="TitlePanel1"Radius="10"></AjaxToolKit:RoundedCornersExtender><AjaxToolKit:CollapsiblePanelExtenderID="CollapsiblePanelExtender1"runat="server"Collapsed="true"SuppressPostBack="false"TargetControlID="ContentPanel1"ExpandControlID="Panel1"CollapseControlID="Panel1"imageControlID="image1"ExpandedImage="~/images/collapse_blue.jpg"CollapsedImage="~/images/expand_blue.jpg"></AjaxToolKit:CollapsiblePanelExtender>............

<

asp:PanelID="ContentPanel1"runat="server"CssClass="collapsePanel"Height="0"Width="728px"><tablestyle="width: 728px"><tr><tdstyle="width: 93px; height: 4px"><asp:ButtonID="Button1A"runat="server"Font-Bold="True"Font-Size="X-Small"ForeColor="Crimson"Text="Get Your PDF"Width="224px"/></td>

Hi,

After a while I have found a workaround for the problem I posted, so I am posting this workaround here in case someone else have the same problem:

Basically I have include a second button (button2) outside the control panel. Once the first button (button1, the one inside the updatepanel) is clicked it fire the next javascript:

<input type="submit" name="Button1" value="Button" onclick="javascript:document.getElementById('button2').click() ;" id="Button1" /><br />

So button1 "clicks" button2 (that is the one outside the updatepanel) and this second button is the one that get the PDF file.

To include the javascript you just need to include the next line (in vb) in the "load" of the page:

button1.Attributes.Add(

"onclick","javascript:document.getElementById('button2').click() ;")

Now i am looking for a way to hidde button2 (notice that in order to click it you can not set visible to false).

Hope this can help someone.

Best,

Jaime

Response.Write with update panel issue

I am having a problem with a response.write in page.load and an atlas update panel. I created a quick sample to repro this issue. What should happen is the ddl loads with the current date. If I run it doing a response.write of the stylesheet in the page.load, it does not work. If I put the stylesheet reference at the top of the webform, it works. The page source rendered in IE is exactly the same, however using fiddler I noticed that the Atlas request on the button click returned different results. The main difference is the response.write way returns what I had in the response.write before the delta tags in the fiddler response.

In my codebehind I have:

PartialClass LiveTestInherits System.Web.UI.PageProtected Sub btnClickMe_Click(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles btnClickMe.Click ddlStuff.Items.Add(New ListItem(Date.Now.ToString))End Sub Protected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.Load Response.Write("<head><link rel=""stylesheet"" type=""text/css"" href="http://links.10026.com/?link="/tools/style0.css""/></head>")End SubEnd Class
Webform
 
<%@dotnet.itags.org. Page Language="VB" AutoEventWireup="false" CodeFile="LiveTest.aspx.vb" Inherits="LiveTest" %><!--head><link rel="stylesheet" type="text/css" href="http://links.10026.com/?link=/tools/style0.css"/></head--><head runat="server"> <title>Untitled Page</title></head><atlas:ScriptManager ID="sm" runat="server" EnablePartialRendering="true"></atlas:ScriptManager><body> <form id="form1" runat="server"> <div> <div class="Heading">This is a test</div> <asp:Button ID="btnClickMe" Text="Click Me" runat="server" /> <br /> <atlas:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:DropDownList ID="ddlStuff" runat="server"></asp:DropDownList> </ContentTemplate> <Triggers> <atlas:ControlEventTrigger ControlID="btnClickMe" EventName="Click" /> </Triggers> </atlas:UpdatePanel> </div> </form></body>
Fiddler Views
(Response.Write Does not work)
<head><link rel="stylesheet" type="text/css" href="/tools/style0.css"/></head><delta><rendering><head><title>....</delta>vs.(Declare stylesheet in html works)
<delta><rendering><head><title>Untitled Page</title><style type="text/css">....</delta>

Is there any kind of workaround for this issue (besides don't response.write your stylesheets)? We dynamically write out different stylesheets based on user preferences in a base page that other web pages inherit from.

Thanks in advance

I found that using

Me.Controls.AddAt(0,New System.Web.UI.LiteralControl("<head>....<style>.....</head>"))

Works fine instead of doing the response.write

Thanks

restarting the autocomplete extender?

hi everyone,

I have an autocomplete textbox and detailsview control inside of update panel with partial rendering enabled. When I use the autocomplete control first the time and click on the search button, the detailsview control loads the data and displays it.

But when delete the textbox and start typing again, it no longer autocompletes. Does this work or is there something wrong with my code.

thanks,

gavin

Code Behind

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 partial class Lookup : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void ButtonLookup_Click(object sender, EventArgs e)
{
DataSet1TableAdapters.StaffTableAdapter TAStaff = new DataSet1TableAdapters.StaffTableAdapter();

DetailsView.DataSource = TAStaff.GetStaffInfoByName(SearchKey.Text);
DetailsView.DataBind();
DetailsView.Visible = true;
}
}

HTML Page

<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Lookup.aspx.cs" Inherits="Lookup" %
<!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 id="Head1" runat="server">
<atlas:ScriptManager runat="server" EnablePartialRendering="true" ID="scriptManager">
</atlas:ScriptManager>
<style type="text/css">
body { font: 11pt Trebuchet MS;
font-color: #000000;
padding-top: 72px;
text-align: center }

.text { font: 8pt Trebuchet MS }
</style>

</head>

<body>
<form id="Form1" action="" runat="server">

<atlas:UpdatePanel ID="Panel2" Mode="Always" runat="server">
<ContentTemplate
<div>
Search for
<asp:TextBox ID="SearchKey" runat="server"></asp:TextBox>
<asp:Button ID="ButtonLookup" runat="server" Text="Lookup" OnClick="ButtonLookup_Click" />

</div>
<hr style='width: 300px'/
<asp:DetailsView ID="DetailsView" runat="server" Height="196px" Width="323px">
</asp:DetailsView>
</ContentTemplate>
</atlas:UpdatePanel
</form>

<div id="completionList"></div>
<div>
<span id="Results">Here's some other text that shouldn't refresh.</span></div
<script type="text/javascript">
function DoSearch()
{
var SrchElem = document.getElementById("SearchKey");
Samples.AspNet.HelloWorldService.HelloWorld(SrchElem.value,
OnRequestComplete);
}

function OnRequestComplete(result)
{
var RsltElem = document.getElementById("Results");
RsltElem.innerHTML = result;
}

</script
<script type="text/xml-script">
<page xmlns:script="http://schemas.microsoft.com/xml-script/2005">
<components>
<textBox id="SearchKey">
<behaviors>
<autoComplete
completionList="completionList"
serviceURL="AutoCompleteService.asmx"
serviceMethod="GetWordList"
minimumPrefixLength="1"
completionSetCount="15"
completionInterval="500" />
</behaviors>
</textBox>
</components>
</page>
</script>
</body>
</htmlHi gfun,

The AutoCompleteExtender isn't part of the Toolkit, so you'll have better luck asking this question in theAJAX UI forum.

Thanks,
Ted

retaining class state.

dear All

I have a checkbox, a dropdownlistbox and a label in 3 separate update panels.

I have autopostback=true for both checkbox and dropdownlist box and write to the label text in their eventhandlers. The checkbox event when fired writes as expected but not the dropdownlistbox.

I have a class called myclass with a string property called "abrev". I want to remember the complete myclass between postbacks. I think there is something called session to do it...but can someone help me on how to do it in the below code?

aspx.cs code.

public partialclass _Default : System.Web.UI.Page { myclass[] pessi =new myclass[10];protected void Page_Load(object sender, EventArgs e) { ScriptManager1.RegisterAsyncPostBackControl(CheckBox1); ScriptManager1.RegisterAsyncPostBackControl(DropDownList1);for (int i = 0; i < 10; i++) { pessi[i] =new myclass(); } }protected void CheckBox1_CheckedChanged(object sender, EventArgs e) { DropDownList1.Items.Clear(); DropDownList1.Items.Add("something"); DropDownList1.Items.Add("something1"); pessi[0].Abrev ="I am in checkbox"; Label2.Text = pessi[0].Abrev; UpdatePanel2.Update(); UpdatePanel3.Update(); }protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { Label2.Text = pessi[0].Abrev; UpdatePanel3.Update(); }}
 
aspx code 
<form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <br /> <br /> <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server"> <ContentTemplate> <asp:CheckBox ID="CheckBox1" runat="server" autopostback="true" OnCheckedChanged="CheckBox1_CheckedChanged" /> </ContentTemplate> </asp:UpdatePanel> <br /> <br /> <asp:UpdatePanel ID="UpdatePanel2" UpdateMode="Conditional" runat="server"> <ContentTemplate> <asp:DropDownList ID="DropDownList1" autopostback="true" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> </asp:DropDownList> </ContentTemplate> </asp:UpdatePanel> <br /> <br /> <asp:UpdatePanel ID="UpdatePanel3" UpdateMode="Conditional" runat="server"> <ContentTemplate> <br /> <br /> <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label> </ContentTemplate> </asp:UpdatePanel> </form>
  
Thank you all in advance,
prasad.. 

Session Variables are what you want. They are are read/write like any other variable, except they persist in memory on the server for the duration of the visitors session. They are also simple to use:

Session["myvar"] = "var";
Response.Write["myvar"]; //will outputvar



hi

Thank you for your reply.

I am a little new to the world of programming and computers as such (not a SW professional). Can you please tell me how to store a complete class?

will this work for my above example?

Session["myname"] = "myclass";

Secondly, where should this session be defined= in pageload? and also when there is a postback?

lastly, I want to be able to change any property of myclass in the code behind when events happen...do these changes automatically take place in the session..

for example...if I change myclass.Abrev (in my example) for a button click event for example then are the session variables updated automatically?

Thank you in advancem

prasad..

retrieve info dynamically created textbox in update panel

I have a textbox that is created in code in an Ajax Update Panel when then the user clicks on a dropdownlist.

I would then like to retreive the text that user types in:

Dim strTitleAsString =CType(Me.FindControl("txtPrimaryPersonTitle" + intSuggestedPrimaryPersonCount.ToString), TextBox).Text

It gives me an error that it can't find the control.

Can you offer any help??

Have you made sure that the textbox is re-created on postback?

You may also consider creating the textbox statically (in markup) instead of dynamically.
Set Visible=False in the markup, and make it visible in your dropdownlist code.
This prevents most of the problems inherent to dynamic controls.

Jos


hello.

how about a demo page so that we can see what you're doing? it has to be simple enough so that we ca simply copy/paste it in order to test it


Hi,

it can't find the control?

If the contorl still exist, the Id must not write.

I think it is easy to debug to see if the contorl is exist or not, and it is easy to find out what is the correct id of the contorl.

If you still have question,post up a repro of your issue.

Best Regards,

Retrieve viewstate during a GET request

I have a page with controls that specify a filter on a set ofresults. I have used ajax and the update panel to show updated resultsthrough asynchronous request when the filter gets updated. When theuser selects an item in the set they navigate to a different page...when they then hit the back button they return to the filter page butall the controls are all re-initialized.

What I've been trying isgenerating an id for the page on the initial request (as is done andnormally placed in a hidden field for my custom PageStatePersister thatkeeps the viewstate in a database) but then redirecting the user to aurl with the id appended. So when you later hit the back button youhave the id in the URL.


Next LoadViewState is NOT calledunless the request is the result of a postback. Well I've been tryingto initialize the ViewState in the Page_Load by callingLoadPageStateFromPersistenceMedium() and that does result in callingthrough my custom PageStatePersister... But the ViewState dictionary ofthe page does not get updated... what am I missing?

Or is there another way to accomplish not losing the filter values?

Ok...this is going to be hard for me to explain..but I shall try. And i will suggest two solutions. First of all remember client side styles are not persisted unless asked, and viewstate track changes to state only when tracking is enabled. So all your controls are reinitialised because tracking gets enabled after oninit() and then viewstate just deserializes the stored data.

So unless you set trackviewState(), viewstate is not tracking anything. (Once on, cannot be turned off) Once tracking is on..viewstates items can be marked dirty(IsItemdirty()). You can also set an item to be dirty. Basically tracking allows viewstate to monitor which of its elements have changed since TrackViewState() has been called. Statebag ignores the items that are not marked dirty when it comes to saving view state SaveViewState() and hence items not marked dirty are not serialized.

So one of the solution is to markitems dirty which you want to be persisted before that postback. The other is dont do it by ajax but by actual user controls.

Just a question for you to ponder, if you have two identical pages with a textbox and a button with on onclicking code.

as <as:textbox runat="server" text="abc"><asp:button runat="server" text="submit">

with other pages only having change in its text property as text="the quick brown fox jumps over the little lazy dog" Do the two pages have same viewstate?

Read this article if you want to understand viewstate.

http://msdn2.microsoft.com/en-us/library/ms972976.aspx


I appreciate your feedback but I'm not sure how it applies... I'm not having problems writing viewstate... I'm having problems loading the viewstate during a GET request. I'll try articulating my problem differently:

1) I've persisted the viewstate on the server side.
2) The viewstate is identified by a hidden field and so is in the form data during a postback (this already works)
3) On the first GET of a page I generate the identifier and redirect the request to a page with the viewstate identifier appended to the URL
4) By default Viewstate is NOT loaded during a GET request only POSTBACK
5) On the first GET of the URL+ViewstateID, the viewstate does not exist and the page runs through normal initialization
6) On subsequent requests to URL+ViewstateID does exist and I want to load this Viewstate from storage (see 4)
7) I've tried Page.LoadPageStateFromPersistenceMedium() which does call my pagestatepersister and retrieves the viewstate... now how do I apply this to the page instance...? can I ...?


before you move on to the next page, you can either save your viewstate as I said in my previous post and write it to a session and later on retreive the session, and put it back in viewstate.

Although this can be accomplished by plain sessions.

return alert msg on ajax call

Hello guys

Quick question. Scenario: I have a update button that does an AJAX call and updates DB. I want to return a success/failure message such that it shows up as an alert message box on UI rather than showing a lblMessage and updating its visiblity and text property. Any suggestions?

Thanks in advance.

Hi There,

Try following:

protectedvoid Button1_Click(object sender,EventArgs e)

{

// Alert with messagebox after callback

// Your process here e.g. add/edit/delete from database and etc

// Assume your process take 5 second to complete

System.Threading.Thread.Sleep(5000);

// Build your alert script

StringBuilder sbScript =newStringBuilder();

sbScript.Append("<script language='JavaScript' type='text/javascript'>");

sbScript.Append("alert('hello world!')");

sbScript.Append("</script>" );

// Make use ScriptManager to register the script

ScriptManager.RegisterStartupScript(this,this.GetType(),"@.@.@.@.MyCallBackAlertScript", sbScript.ToString(),false);

}


Hi,

You can write a javascript function taking a string parameter on your page having an alert function call displaying the message in the parameter. I have posted a similar solution in this forum. You can have a look at that. I hope you find it useful. It is at http://forums.asp.net/t/1122462.aspx .

If you have any problem in that, let us know.



Thanks for this d4dennis..it worked..but I am not happy man yet. I have two questions..first, on postback is this still sitting on the client page. If so, is there any chance it might called again unwantedly?

Second, I was hoping to trap the Sys object of ajax. I have seen that when there is an exception thrown, it shows up as an alert message on screen. I want to somehow be able to trap that guy. Any ideas there? sorry for being so picky but that's what I want.

This works and right now to continue, I am using this. thanks again.


Hi There,

This is the solution i can think of.

tinuverma:

First, on postback is this still sitting on the client page. If so, is there any chance it might called again unwantedly?

THIS WILL NOT POP UP ON POSTBACK

tinuverma:

Second, I was hoping to trap the Sys object of ajax. I have seen that when there is an exception thrown, it shows up as an alert message on screen. I want to somehow be able to trap that guy. Any ideas there? sorry for being so picky but that's what I want.

IM NOT SURE THIS IS ACHIEVEABLE, IF SOMEONE HAVE ANY IDEA. ANYWAY, YOU CAN RAISE THIS AS ANOTHER QUESTION.

2012年3月24日土曜日

Returning Values with DynamicPopulateExtender

Hi guys,I need to update two different values on a page, which I'd like to calculate at the same time (Monthly Value and Annual Value). Is it possible to get DynamicPopulateExtender to return two values for different controls?It's not a simple case of *12 for Annual value, and it would really reduce processing time if I could calculate both at the same time.Andi

From what I understand, I don't think so. What about just using two UpdatePanels?

Rich text editor in an update panel

I want to use a javascript editor like fckeditor in my webpage where the textarea is in an updatepanel.

But the textarea isn't is the welcome page, she apear when you click on a linkbutton.

How can i do for the editor to trigger when the textarea come or for the editor to load when i click the link.

Thanks in advance.I NEED YOU, HELP ME PLEASE

Rollovers with update panel not working?

Hello all,

I got a master page which containsjavascript generated by imageready for the rollover effect. I have acontent page which contains textbox, image button, updatepanel (Atlas)with Partial Rendering=True and gridview. Everything works fine in thebeginning. But once I sort, filter the grid view, the grid viewchanges as it should but now my rollovers don't work. I seems that thefunction that the onmouseover is not firing. I can still mess with thegridview that works fine. Oh yea the image button also has rolloverstate, that works but that is not calling the imageready function. Ithas inline javascript onmouserover="this.src='imgOver.gif';". I'malittle confused why the functions are not firing after the callback. Any ideas will be appreciated.

Thank YouPhotoshop's generated javascript uses a global boolean variable calledpreloadFlag. It sets this value to false globally, so I guess when a call back happens this line was being executed and sset back to false from being true. So none of the rollovers worked. I set it to true and the roll overs worked.

Hi boricua,

Here's a procedure you can adapt to your needs. Just call it for each ImageButton from the Page_Load. I've only tested this on IE 6, so let me know if it gives you any trouble.

ProtectedSub Page_Load(ByVal senderAsObject,ByVal eAs System.EventArgs)HandlesMe.LoadIfNot (Page.IsPostBack)Then

rollover3State(imgArrowLeft,

"ArrowLeft")
rollover3State(imgArrowRight,"ArrowRight")EndIfEndSubProtectedSub rollover3State(ByVal btnObjectAs ImageButton,ByVal baseImageAsString)

btnObject.Attributes.Add(

"onmouseout","{this.src='" &Me.ResolveUrl("App_Themes/" &Me.StyleSheetTheme &"/images/btn_" & baseImage &"_0.gif") &"';}")

btnObject.Attributes.Add(

"onmouseover","{this.src='" &Me.ResolveUrl("App_Themes/" &Me.StyleSheetTheme &"/images/btn_" & baseImage &"_1.gif") &"';}")

btnObject.Attributes.Add(

"onmousedown","{this.src='" &Me.ResolveUrl("App_Themes/" &Me.StyleSheetTheme &"/images/btn_" & baseImage &"_2.gif") &"';}")EndSub

Yeah this works. I used this method on some pages that I manually created, but for the ones that the html was created by imageready, which creates the javascript as well I fixed with the method I described earlier thank you dbDan.

2012年3月21日水曜日

RoundedCornersExtender and DropDownList Causing Update Panel to Flash

I have run into a problem when I use the RoundedCornersExtender on an updatepanel. Everything functions as expected unless a DropDownList is contained on the container the RoundedCornersExtender is being applied to. If I place a DropDownList on the Div, on any partial post back, the entire page flashes. It still performs only a partial postback, but it appears that the entire page is being re-rendered. In this simple example it is only the update panel, but on my larger page (multiple divs, tables, etc) it seems all objects on the page flash.

Any help would be appreciated.

In Firefox, it seems to work fine, but I seem to be able to reproduce this problem with ease in Internet Explorer 6.

In my sample code, I have a button that does a simple postback and increments the count displayed in the label by 1.

<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<cc1:RoundedCornersExtender ID="RoundedCornersExtender1" runat="server" Radius="6" Color="Blue" TargetControlID="MyContentDiv" />

<div id="MyContentDiv" runat="server" style="background-color: Red">

This is my content inside the div.

<asp:DropDownList ID="DropDownList1" runat="Server" />

</div>

<asp:Label ID="lblCounter" runat="Server">0</asp:Label>

<asp:Button ID="cmdCount" runat="server" OnClick="cmdCount_Click" Text="Count"></asp:Button>

</ContentTemplate>

</asp:UpdatePanel>

protected void cmdCount_Click(object sender, EventArgs e)
{
int tmpVal = 0;
int.TryParse(this.lblCounter.Text,out tmpVal);
tmpVal++;
this.lblCounter.Text = tmpVal.ToString();
}

Feel a little sheepish on this one. I incorrectly assumed that because it was so specific to having drop downs, something really screwy was going on. This was solved with the whole Setting Debug=False Solutions.

Cheers


Ok, now maybe I am going crazy. It seems to be happening again... Has anyone else been able to reproduce this problem?
I am having the same issue, roundedcornersextender or dropshadowextender with rounded corners are both causing the entire screen to flash when a dropdownlist or listbox are on the page. This must be a bug, I am using beta2, removing the rounded corners makes it go away
hey I am also getting same issue...any update on this?

Hi,

I am also having this problemCrying, hope someone from asp.net team or Microsoft ASP.NETAJAX team member will look into this problem seriously.

Kind Regards,

Dev


I'm just going to chime in for a October 2007 update that I am having this problem as well...

RoundedCornersExtender causes this same problem in my app... All that is in my UpdatePanel is a Gridview. Everything works as expected in Firefox 2.0.0.7 but I get the flash/reload with Internet Explorer 6.0.29. After this happens the Gridview is hidden from the screen. If I remove the RoundedCornersExtender, everything works fine.


By the looks of it, this seems to be a common issue. I'm using an updatepanel with the collapsiblepanel and it works great! Now, if I add any type of changing control such as a DropDownList or ListBox, the flashing beginsConfused. I came up with an alternative for the dropdownlist which was a navigational menu; bad idea! I click on the menu and all the other menus become frozen or won't refresh. So canned that idea. At this point I'm ready to trash the whole thing and start from scratch, let the whole thing flash! I hope this can be figured out.

JZee