Showing posts with label load. Show all posts
Showing posts with label load. Show all posts

Wednesday, March 28, 2012

Extenders briefly appearing on a page load

Hi there

I am using the modalpopup and calender extenders from the toolkit in my ASP.NET code.

The page they are on is a content page (I am using master pages).

They both work. However, when the page initially loads the extender(happens on both) flickers on the screen and then hides itself!?!?!

Does anyone have any ideas?

Many thanks

Mike

Hi Mike,

It seems a full postback is occurring according to your description. Please make sure the targetControlid is properly set the button that triggers a full postback.


Hi there

Thanks for the help. I have set the control IDs correctly.

The calender popup I have working, I had to set the visibility to false in the style.

However, for the modal popup I tried this and it doesn't show up at all.

Any more ideas I can try to stop the modal popup from flickering initially??

Cheers

Mike


Try setting the style as... style="display: none;"


Can you post a stripped sample?


Hi

I tried that also and it stops my popup from being displayed at all. (However, on a side note, when I do do this, as well as not showing my poopup it seems to keep adding "invisible" stuff to the side of my page, makes my scroll bars appear and the page keeps getting wider and wider!!! Very very strange and freaky!!!)

The code for my modalpopup is:


 <asp:Button runat="server" ID="testbut" text="popup test" OnClick="testbut_Click" CssClass="hiddenbutton"/> <asp:Panel ID="Panel1" runat="server"> <asp:Panel ID="Panel3" runat="server" CssClass="modalPopup"> <div> <p class="title">AudioPC Navigator</p> <br /> <p> AudioPC Navigator will launch each Audiosoft component into a new window, but supports tabbed browsing if your browser is configured to do so. </p> <br /> <p> For details on how to set your system to tabbed browsing <a onclick="help('TabbedBrowsing');return false;">click here</a> </p> <br /> <p> <input type="checkbox" name="check" id="InitialHelpCheckbox" /> <label for="InitialHelpCheckbox" class="sampleStyleC" style="padding: 3px;">Do not show this message again</label> </p> <br /> <p style="text-align: center;"> <asp:Button ID="OkButton" runat="server" Text="OK" /> </p> </div> </asp:Panel> </asp:Panel> <ajaxToolkit:ModalPopupExtender ID="InitialHelpModalPopup" runat="server" PopupControlID="Panel1" BackgroundCssClass="modalBackground" OkControlID="OkButton" OnOkScript="onOk()" DropShadow="true" Drag="true" PopupDragHandleControlID="Panel3" TargetControlID="testbut"/>

<asp:Button runat="server" ID="testbut" text="popup test" OnClick="testbut_Click" CssClass="hiddenbutton"/>

<asp:Panel ID="Panel1" runat="server">
<asp:Panel ID="Panel3" runat="server" CssClass="modalPopup">
<div>
<p class="title">AudioPC Navigator</p>
<br />
<p>
AudioPC Navigator will launch each Audiosoft component into a new window, but supports tabbed browsing if your browser is configured to do so.
</p>
<br />
<p>
For details on how to set your system to tabbed browsing <a onclick="help('TabbedBrowsing');return false;">click here</a>
</p>
<br />

<p>
<input type="checkbox" name="check" id="InitialHelpCheckbox" />
<label for="InitialHelpCheckbox" class="sampleStyleC"
style="padding: 3px;">Do not show this message again</label>
</p>
<br />
<p style="text-align: center;">
<asp:Button ID="OkButton" runat="server" Text="OK" />
</p>
</div>
</asp:Panel>
</asp:Panel>


<ajaxToolkit:ModalPopupExtender ID="InitialHelpModalPopup" runat="server"
PopupControlID="Panel1"
BackgroundCssClass="modalBackground"
OkControlID="OkButton"
OnOkScript="onOk()"
DropShadow="true"
Drag="true"
PopupDragHandleControlID="Panel3"
TargetControlID="testbut"/>

And the style for the popup is:

.modalPopup {
background-color:#e4e4e4;
border-width:1px;
border-style:solid;
border-color:Black;
padding:1px;
width:350px;
}

Any more ideas?

Thanks in advance

Mike


Why I can't see the flicker thing ? My code:

<%@. 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 testbut_Click(object sender, EventArgs e) { }</script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title> <style type="text/css"> .modalPopup { background-color:#e4e4e4; border-width:1px; border-style:solid; border-color:Black; padding:1px; width:350px;} </style></head><body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:Button runat="server" ID="testbut" text="popup test" OnClick="testbut_Click" CssClass="hiddenbutton"/> <asp:Panel ID="Panel1" runat="server"> <asp:Panel ID="Panel3" runat="server" CssClass="modalPopup"> <div> <p class="title">AudioPC Navigator</p> <br /> <p> AudioPC Navigator will launch each Audiosoft component into a new window, but supports tabbed browsing if your browser is configured to do so. </p> <br /> <p> For details on how to set your system to tabbed browsing <a onclick="help('TabbedBrowsing');return false;">click here</a> </p> <br /> <p> <input type="checkbox" name="check" id="InitialHelpCheckbox" /> <label for="InitialHelpCheckbox" class="sampleStyleC" style="padding: 3px;">Do not show this message again</label> </p> <br /> <p style="text-align: center;"> <asp:Button ID="OkButton" runat="server" Text="OK" /> </p> </div> </asp:Panel> </asp:Panel> <ajaxToolkit:ModalPopupExtender ID="InitialHelpModalPopup" runat="server" PopupControlID="Panel1" BackgroundCssClass="modalBackground" OkControlID="OkButton" OnOkScript="onOk()" DropShadow="true" Drag="true" PopupDragHandleControlID="Panel3" TargetControlID="testbut"/> </div> </form> </body></html>

Extended controls may not be registered before Pre-Render

hi all,

i get the following error message when trying to load a usercontrol containing a modalpopupextender:
"extended controls may not be registered before pre-render"

no line specified, no more info about what's wrong, and almost everything is done with click 'n' drag in design mode (vwd 2005).

default.aspx and its codebehind:http://www.aspsidan.se/code/default.asp?c=9359

editcontent.ascx and its codebehind:http://www.aspsidan.se/code/default.asp?c=9361

the error message:http://www.aspsidan.se/code/default.asp?c=9360

editcontent.ascx is, as you can see, within a loginview, and it's not until i log on that i get the problem. i guess this error has something to do with the page life cycle, but i have no clue of how to get around it...

(i posted the code already in another forum, so i refer to those pages. i hope they're available even if you're not logged on. i've tried when i was offline and it worked, so it shouldn't be a problem...)

Hi lycken,

It is a common issue. You should add base.OnPreRender at the beginning ofvoid OnPreRender(EventArgs e){};

For more , pleaseread this. If it doesn't work, please feel free to let me know.

Best regards,

Jonathan


hi jonathan,

thanks a lot for the reply! it really does save my day that there is a solution to this.

however, neither your answer nor the article you linked me to helped me all the way. i understand i have to call the base.OnPreRender routine, but i can't figure out where in my code to put the call. i am coding in vb, so if you could explain it with vb examples instead of c# it would help me ;)

thanks again for your help!

-tomas


Hi Lycken,

Would you please give us a tiny and workable repro? So you can benefit from it directly. Thanks for your understanding.

Best regards,

Jonathan


hi again jonathan,

i provided all my source code in the first post - unless the links are not working. it's pasted below anyway - excuse the lenghtyness... and again - thanks for helping out!

the db is designed as follows:

Texts
******
TextID | int (identifier, primary key)
TextName | varchar(15)
Text | varchar(max)

Default.aspx

1<%@. Page Language="VB" MasterPageFile="~/site.master" AutoEventWireup="false" CodeFile="Default.aspx.vb"Inherits="_Default" title="Untitled Page" Theme="SMK" Trace="true" %>
2<%@. RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
3<%@. Register TagPrefix="list" TagName="Concerts" src="~/konsertprogram/Concerts.ascx" %>
4<%@. Register TagPrefix="ucl" TagName="EditContent" src="~/admin/EditContent.ascx" %>
5
6<asp:Content ID="Content1" ContentPlaceHolderID="Left" Runat="Server">
7 <asp:Image ID="LeftPaneImage" runat="server" ImageUrl="~/image/bredvid_konserter.jpg" />
8</asp:Content>
9<asp:Content ID="Content2" ContentPlaceHolderID="Content" Runat="Server">
10 <asp:Label ID="TextLabel" runat="server" />
11 <div style="text-align:right; width:100%;">
12 <asp:LoginView ID="LoginView1" runat="server">
13 <RoleGroups>
14 <asp:RoleGroup Roles="Admin">
15 <ContentTemplate>
16 <ucl:EditContent ID="EditContentUserControl" runat="server" TextToEdit="hem" />
17 </ContentTemplate>
18 </asp:RoleGroup>
19 </RoleGroups>
20 </asp:LoginView>
21 </div>
22
23 <div class="row">
24 <div style="float:left;">
25 <h1>N?sta konsert:</h1>
26 <list:Concerts ID="Concerts" runat="server" ItemsToShow="1" />
27 </div>
28
29 <div style="float:left;">
30 <h1>En till ruta</h1>
31 <p>med lite info</p>
32 </div>
33 </div>
34
35</asp:Content>

Default.aspx.vb

1Imports System.Configuration
2Imports System.Data.SqlClient
3Imports System.Data.SqlDbType
4Imports ErrorHandling
5
6PartialClass _Default
7Inherits System.Web.UI.Page
8
9Dim objConnAs New SqlConnection(ConfigurationManager.ConnectionStrings("SMK").ConnectionString)
10
11Protected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.Load
12Dim objCmdAs New SqlCommand("SELECT [Text] FROM [Texts] WHERE [TextName] ='hem'", objConn)
13
14Try
15 objConn.Open()
16 TextLabel.Text = StringFunctions.FormatText(objCmd.ExecuteScalar)
17Catch exAs Exception
18 Err.Log(ex)
19Finally
20 If objConn IsNotNothing Then objConn.Close()
21End Try
22 End Sub
23End Class

EditContent.ascx

1<%@. Control Language="VB" AutoEventWireup="false" CodeFile="EditContent.ascx.vb"Inherits="admin_EditContent" %>
2<%@. RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
3<asp:ScriptManager ID="ScriptManager1" runat="server">
4</asp:ScriptManager>
5<asp:LinkButton ID="EditText" runat="server" CssClass="textr">Redigera texten</asp:LinkButton>
6<asp:Panel ID="ModalPanel" runat="server" CssClass="modalpu">
7 <asp:Button ID="btnBold" runat="server" Font-Bold="True" Text="F" Width="30px" />
8 <asp:Button ID="btnItalic" runat="server" Font-Italic="True" Text="K" Width="30px" />
9 <asp:Button ID="btnUnderline" runat="server" Font-Underline="True" Text="U" Width="30px" />
10 <asp:Button ID="btnHeader" runat="server" Text="Rubrik" Width="80px" />
11 <asp:Button ID="btnText" runat="server" Text="Text" Width="80px" /><br />
12 <asp:TextBox ID="tbContent" runat="server" Height="400px" Width="430px" TextMode="MultiLine" /><br />
13 <asp:Button ID="OKButton" runat="server" Font-Bold="True" Text="Skicka" Width="90px" />
14 <asp:Button ID="CancelButton" runat="server" Text="Avbryt" Width="90px" /><br />
15 <asp:Label ID="lblStatus" runat="server" />
16</asp:Panel>
17<cc1:ModalPopupExtender ID="ModalPopupExtender" runat="server"
18 TargetControlID="EditText"
19 PopupControlID="ModalPanel"
20 x="0"
21 Y="0"
22 DropShadow="true"
23 RepositionMode="none"
24 OkControlID="OKButton"
25 OnOkScript="__doPostBack('ctl00$Content$LoginView1$EditContentUserControl$OKButton','')"
26 CancelControlID="CancelButton"
27 BackgroundCssClass="modalbg" />
EditContent.ascx.vb
1Imports System.Configuration
2Imports System.Data.SqlClient
3Imports System.Data.SqlDbType
4Imports ErrorHandling
5
6PartialClass admin_EditContent
7Inherits System.Web.UI.UserControl
8
9Dim objConnAs New SqlConnection(ConfigurationManager.ConnectionStrings("SMK").ConnectionString)
10Private _textToEditAs String
11
12 Public WriteOnly Property TextToEdit()As String
13 Set(ByVal valueAs String)
14 _textToEdit = value
15End Set
16 End Property
17
18 Protected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.Load
19Dim objCmdAs New SqlCommand("SELECT [Text] FROM [Texts] WHERE [TextName] = @.TextName", objConn)
20
21Dim objParamAs New SqlParameter("@.TextName", VarChar)
22 objParam.Value = _textToEdit
23 objCmd.Parameters.Add(objParam)
24
25Try
26 objConn.Open()
27 tbContent.Text = objCmd.ExecuteScalar
28Catch exAs Exception
29 Err.Log(ex)
30Finally
31 If objConn IsNotNothing Then objConn.Close()
32End Try
33 End Sub
34
35 Protected Sub OKButton_Click(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles OKButton.Click
36Dim objCmdAs New SqlCommand("UPDATE Texts SET [Text] = @.Text WHERE [TextName] = @.TextName", objConn)
37
38Dim objParamAs New SqlParameter("@.Text", VarChar)
39 objParam.Value = tbContent.Text
40 objCmd.Parameters.Add(objParam)
41
42 objParam =New SqlParameter("@.TextName", VarChar)
43 objParam.Value = _textToEdit
44 objCmd.Parameters.Add(objParam)
45
46Try
47 objConn.Open()
48 objCmd.ExecuteNonQuery()
49 lblStatus.Text ="Uppdaterat!"
50Catch exAs Exception
51 Err.Log(ex)
52Finally
53 If objConn IsNotNothing Then objConn.Close()
54End Try
55
56 objConn =Nothing
57 objCmd =Nothing
58 End Sub
59End Class



Hi Luken,

Would you please add this code to EditContent.ascx.vb?

protected override void OnPreRender(EventArgs e)
{
// add base.OnPreRender(e); at the beginning of the method.
base.OnPreRender(e);

// codes to handle with your controls.
...
}

I have copied your code to my project and did some modifications(comment and rename work only) , it works well on my machine. Also where's your master page? If it doesn't work, would you please create aworkable sample and give us the links so that we can download your project. Thanks

Best regards,

Jonathan


i'd love to add it to editcontent.ascx.vb, but i don't know how to re-write it to vb. i get syntax errors on "base" when i try. what is it called with vb syntax?


Hi Lycken,

For example,

C# code

protected override void OnPreRender(EventArgs e)
{
// add base.OnPreRender(e); at the beginning of the method.
base.OnPreRender(e);

// codes to handle with your controls.
...
}

Convert to VB Code,

Protected Overloads Overrides Sub OnPreRender(ByVal e As EventArgs) ' add base.OnPreRender(e); at the beginning of the method. MyBase.OnPreRender(e) ' codes to handle with your controls.

End Sub

Here is anuseful tool.

I hope this help.

Best regards,

Jonathan


thanks a lot! it's working fine now - or at least this part of the solution is... i have a couple of other things that aren't doing so well at the moment, but i'll work on those for yet a while before i post here.

again, thanks!

Monday, March 26, 2012

Executing inline JavaScript on load

I have a rather complex ASP.NET control -WebDialog - that I'm trying to get working within Atlas' UpdatePanel.

The way the control currently works is by outputting JavaScript in its render method which is executed by the browser on load. The problem is that when an UpdatePanel is refreshed Atlas doesn't seem to execute inline scripts and so nothing happens.

I have tried moving outputting the JavaScript from the control's render method to its PreRender and then passing the script to RegisterClientScriptBlock, which Atlas does execute. While this method works great in simple scenarios, when the dialog has form controls like TextBox and Button it errors. Since I'm manually calling RenderControl on the nested content, and outside of the form's render, VerifyRenderingInServerForm throws an exception.

I don't want everyone who uses the control to have to use a custom page with VerifyRenderingInServerForm overridden.

Is there a solution that will update when an UpdatePanel refreshes yet works with forms controls and isn't obtrusive to the user developer?

hello.

i doubt it...i think that the only option is sending the javascript to the client though the clientscriptmanager class...


If I did that then I'd be dependant upon Atlas and have to include it's dll with my installer and output all it's JavaScript to the page which I don't want to do.
From what I'm reading, I believe that your JS code is registering with the window's onload event. The first time your page loads the window.onload event occurs, but subsequent partial postbacks don't cause the window.onload event to occur again.

Your thoughts of registering the script with RegisterClientScriptBlock (or RegisterClientStartupScript) seem to be on the right path. I'm not real sure from your posts why your having to manually call RenderControl (shouldn't the controls be added to the parent control's control collection?), but executing inline JS code on load is possible on an UpdatePanel refresh by registering with the ClientScriptManager.

- Joel

hello.

James Newton-King:

If I did that then I'd be dependant upon Atlas and have to include it's dll with my installer and output all it's JavaScript to the page which I don't want to do.

hum...i'm following you...you say that you don't want to be dependant upon atlas ( i think you're talking about the server side dll?)...but you also say that you have the control placed inside an updatepanel. the only way you'll use a panel is if you add the atlas dll to your app!

one more thing: if you're using asp.net (i assume you are) then you can use the clientscriptmanager without any problems since it was introduced in asp.net 2.0 to handle client script registration.


Luis Abreu:

hello.

James Newton-King:

If I did that then I'd be dependant upon Atlas and have to include it's dll with my installer and output all it's JavaScript to the page which I don't want to do.

hum...i'm following you...you say that you don't want to be dependant upon atlas ( i think you're talking about the server side dll?)...but you also say that you have the control placed inside an updatepanel. the only way you'll use a panel is if you add the atlas dll to your app!

one more thing: if you're using asp.net (i assume you are) then you can use the clientscriptmanager without any problems since it was introduced in asp.net 2.0 to handle client script registration.


Obviously if the dialog was inside an UpdatePanel then the app would be using Atlas but this control is also for regular ASP.NET 2.0 users. They're the reason I don't want to become dependant upon Atlas.

Sorry, I confused the ScriptManager in Atlas with the ClientScriptManager in ASP.NET 2.0. I am already using the ClientScriptManager (RegisterClientScriptBlock is a method on it) to register the script so I thought you must have meant the Atlas one. The problem I'm having using RegisterClientScriptBlock is that when I register the JavaScript and render the html in PreRender, ASP.NET throws an exception. It doesn't allow form form controls to be rendered outside of the form.

Anyway, I've come up with a solution that appears to work:
I'm rendering the HTML like you usually would on a page but inside a hidden div and outputting the other JavaScript using RegisterStartUpScript so that it works with Atlas's UpdatePanel. When the dialog is displayed I copy the HTML out from the hidden div into the dialog.

Execute UpdateProgress after page load

I have UpdatePanel, Grid and UpdateProgress controls, all working together using Ajax. When user does any action with the grid, Updateprogress shows nice animated gif "Loading adata...".

However, when the page loads, it takes 5 minutes to load data to the grid. There is no message, nothing, so the user may think he has Internet connection problems... How can I make Updateprogres to show the animated gif, when the page is initially loading data to the grid?

I was thinking maybe there is some event after the page loads, in this case I could load the data, after the page loads... Is it possible? What is the standard way to do it? Thanks

Hi rfurdzik,

When you want to have influence in the partial rendering of your page take a look at this:

http://ajax.asp.net/docs/overview/PageRequestManagerOverview.aspx

The PageRequestManager is the place to be to customize your partial rendering.

Regards,


In your case i would suggest to take a look at the: PageLoading event

"The pageLoading event is raised after the response from the server to an asynchronous postback is received but before any content on the page is updated. You can use this event to provide a custom transition effect for updated content."

Regards,


Hi I am not sure if that is what I need, I looked briefly at the link you gave me, but it seemsit points to PostBacks... I have no postback, this is the first time grid is loading. No user interaction occured yet, no postbacks. With postback works fine, just the initial load of data to the grid needs animation.

I am little bit lost in the info you gave me, would you guide me what event needs to be coded exactly and how to show the animation (I placed it in ProgressPanel)? Here is my scenario:

1) Page Loads

2) Animation shows "Loading data", grid is not visible yet

3) Data is loaded to the grid

4) Animation disappears

As I said earlier this is the initial load, first visit to the page, no postback yet...


There are two solutions:

The first you hide the gridview till the page completely loads and show only a progress image as shown below:

--------

<%@. 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>Sales Details</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div id="Progress"><img alt="Loading..." src="indicator.gif" /> Loading... </div>
<div id="GridContainer" style="display:none">
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString%>" SelectCommand="SELECT TOP (10000) SalesOrderID, SalesOrderDetailID, CarrierTrackingNumber, OrderQty, ProductID, SpecialOfferID, UnitPrice, UnitPriceDiscount, LineTotal, rowguid, ModifiedDate FROM Sales.SalesOrderDetail"></asp:SqlDataSource>
</div>
</form>
<script type="text/javascript">
Sys.Application.add_init(function() {
$get("GridContainer").style.display = "";
$get("Progress").style.display = "none";
});
</script>
</body>
</html>

----------

The second solution is to induce a postback in load. In the sample below it is done by using a Timer control in the UpdatePanel. The GridView is not set to visible when the Page is not in PostBack and as soon as the timer starts a postback is done causing a partial page update which eventually causes UpdateProgress to be shown:

<%@. Page Language="C#" AutoEventWireup="true" %><script runat="server"> protected void Page_Load(object sender, EventArgs e) { GridView1.Visible = IsPostBack; Timer1.Enabled = !IsPostBack; }</script><!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>Sales Details</title></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <asp:UpdateProgress ID="Progress" runat="server"> <ProgressTemplate> <div> <img alt="Loading..." src="indicator.gif" />Loading...</div> </ProgressTemplate> </asp:UpdateProgress> <asp:UpdatePanel ID="GridContainer" runat="server"> <ContentTemplate> <div id="Div1"> <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString%>" SelectCommand="SELECT TOP (10000) SalesOrderID, SalesOrderDetailID, CarrierTrackingNumber, OrderQty, ProductID, SpecialOfferID, UnitPrice, UnitPriceDiscount, LineTotal, rowguid, ModifiedDate FROM Sales.SalesOrderDetail"> </asp:SqlDataSource> </div> <asp:Timer ID="Timer1" runat="server" Interval="100"> </asp:Timer> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" /> </Triggers> </asp:UpdatePanel> </form></body></html>


I think what youare reffering to is custom transition effect after postback. I have this functionality already done using Update panel and UpdateProgress controls. It all works.

What I need is to have the animation (under UpdateProgress) to be displayed during the INITIAL load of the page.

I was thinking maube no Ajax is needed in this case, maybe this can handled by standard ASP.NET code. Something like this (I am not sure what exactly events are):

1) Page load event - display animation (visble property = true), make grid invisible

2) Page loaded (?) - load data, (make grid visible, hide animation)

3) Postback - since I am changing the code now, not sure how the existing Ajax controls will behave (UpdatePanel + UpdateProgress...)


Hi rfurdzik,

Sorry that i didn't understand your question right. The option here above could give you a solution.

Regards,


yes, yes, your code makes sense. Thanks a lot!!! At least you understood what I need!

Dear Rama,

I like the second solution, it is very elegant. I do not fully understand the first one, but it is OK. I think your second solution needs to be modified in my case little bit. I am thinking to do this:

protected void Page_Load(object sender, EventArgs e)
{

if (IsPostback) {

LoadGridData();

}

GridView1.Visible = IsPostBack;

Timer1.Enabled = !IsPostBack;
}

As you see I have added additional if statement for loading the data to the grid, as showing the grid is not enough. Maybe that is why I was confused by the first example... Because I was thinking that even if youhide the grid,data load will occur, which will slow down my page load anyway... Maybe there is something I do not understand there...

However second solution seems will work for me...

Do you guys have some librarries with code? How do you find this? Do you organize your favorities in IE? That new IE is killing me, in version 7 it is so difficult to browse/bookmark anything if you have so many favorities. the reason is that it is all expended by deafault...


Oh, it is OK, your intention is the most important. You wanted to help! I may have not communicated well what I needed:) Thanks anyway for great info.

I have realized that the proposed second solution may also need to be changed more. This is the code I have in Page_Load:

if ((!Page.IsPostBack))

{

LoadData(15);

ViewState[

"CurrentTab"] ="0";// display the grid

}

As you can see I already check for Postback, I only load the data when it is first time load. This is of course for optimization purpose.

So now if I add timer code, we want the load of data to occur in THE FIRST POSTBACK ONLY. Not the first time the form is loading, but the first time postback is generated (by timer control). How would I acomplish this? I was thinking maybe setup a flag? I try this code, but it does not complie (I think some C# syntax issues, I am new to C#:))

m_DataLoaded = ((

Boolean)Session["m_DataLoaded"])=null ?true :false;

if ((Page.IsPostBack) & !(m_DataLoaded))

{

LoadData(15);

ViewState[

"CurrentTab"] ="0";

m_DataLoaded =

true;// display the grid

}

Session[

"m_DataLoaded"] = m_DataLoaded;

grdMyGrid.Visible = IsPostBack;

Timer1.Enabled = !IsPostBack;

What is wrong here? Something with casting I think... Please help.


Hirfurdzik ,

I used SqlDataSource control to bind to the grid which automatically binds the data provided the Grid is visible. So no penalty will be incurred.


Yes, I understand now. I can't figure this out what is wrong with my code, it compiles now, but getting error: m_DataLoaded = ((Boolean)Session["m_DataLoaded"])==null ? true : false; if ((Page.IsPostBack) & !(m_DataLoaded)) { LoadData(15); ViewState["CurrentTab"] = "0"; m_DataLoaded = true; // display the grid } Session["m_DataLoaded"] = m_DataLoaded; grdMyGrid.Visible = IsPostBack; Timer1.Enabled = !IsPostBack;This is the error:Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.Source Error: Line 96: m_dvInv = (DataView)(Session["m_dvInv"]);Line 97: Line 98: m_DataLoaded = ((Boolean)Session["m_DataLoaded"])==null ? true : false;Line 99: Line 100: if ((Page.IsPostBack) & !(m_DataLoaded))

Just changed editor back, beacuse the other one does not format. This one has some delay when typing, so many misstakes...

Yes, I understand now. I can't figure this out what is wrong with my code, it compiles now, but getting error:

m_DataLoaded = ((Boolean)Session["m_DataLoaded"])==null ? true : false;

if ((Page.IsPostBack) & !(m_DataLoaded))
{
LoadData(15);
ViewState["CurrentTab"] = "0";

m_DataLoaded = true;
// display the grid
}

Session["m_DataLoaded"] = m_DataLoaded;

grdMyGrid.Visible = IsPostBack;
Timer1.Enabled = !IsPostBack;


This is the error:

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 96: m_dvInv = (DataView)(Session["m_dvInv"]);
Line 97:
Line 98: m_DataLoaded = ((Boolean)Session["m_DataLoaded"])==null ? true : false;
Line 99:
Line 100: if ((Page.IsPostBack) & !(m_DataLoaded))



m_DataLoaded = ((Boolean)Session["m_DataLoaded"])==null ? true : false;

should be

m_DataLoaded = Session["m_DataLoaded"] ==null ? true : false


Thank you Rama Khrishna, it compiles fine and runs fine now. However the grid is not visible. So eighter the timer did not start, or something wrong with the logic. I will debug it now...

execute function on page load

hi,

I've a javascript function that uses a webservice to fill a dropdown box. I want to call this method when my page is loaded (ie <body onload="..."> but when I do this, Atlas never finds the javascript object that represents my webservice.
I guess this is because this object gets initialized a little later. Does anyone have an idea how I could solve this?

Thanks a lot, Hannes.

Hi Hannes

You can set the load property on the atlas xml-script section to specify you javascript function to execute when the page load. For example:

<script type="text/javascript">
function onLoad(){
alert("Hello, run your code here!");
}
</script>

<script type="text/xml-script">
<page xmlns:script="http://schemas.microsoft.com/xml-script/2005">
<components>
<application load="onLoad">
</application>
</components>
</page>
</script>

Take a look athttp://blogs.msdn.com/jhawk/archive/2006/01/20/515590.aspx for the complete example.

thanks
-jhawk


ah, that's exactly what I was looking for. Thanks a lot, jhawk.

Saturday, March 24, 2012

Exclude page_load during ajax content pannel update possible?

I have this in my behind:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText(String.Format("{0:yyyy}", DateTime.Now).ToString()))
End Sub

The problem is, whenever I select a new value in my drop down list, it defaults itself back to the current month. Is there a way to exclude this from running when I am using an ajax update panel?

You can use Page.IsPostback for this. It is false for the very first request, and true for any postback (also true for async postback)

If you need to determine whether you have a full or an async postback, you can use:IsInAsyncPostBack


If anyone was curious as to how the syntax looked here it is. Worked like a charm. Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If (Page.IsPostBack = False) Then DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText(String.Format("{0:yyyy}", DateTime.Now).ToString())) End If End Sub

Wednesday, March 21, 2012

Error25Could not load file or assembly Microsoft.Web.Extensions, Version=1.0.61025.0, Cult

Hi there,

I am just trying to learn AJAX at the moment and have run into a problem. I have copied over the example for cascading dropdowns and this is where I have the above error.
The error occurs in the web.config file on this line

<

addassembly="Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

Can anyone advise what I need to change?

The sample is for old ajax version.

you need to copy latest ASP.NET AJAX web.config to your projects web.config

below is my cascading code for new version for you

ASPX

<%@. Page Language="C#" AutoEventWireup="true" Codebehind="Default.aspx.cs" Inherits="CascadingDropDownDemo._Default" EnableEventValidation="false" %>

<%@. Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<!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">
<asp:ScriptManager ID="sm" runat="server">
</asp:ScriptManager>
<div>

<asp:UpdatePanel ID="upMain" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddl1" runat="server" Width="275px">
</asp:DropDownList><br />
<asp:DropDownList ID="ddl2" runat="server" Width="275px">
</asp:DropDownList><br />
<asp:DropDownList ID="ddl3" runat="server" Width="275px">
</asp:DropDownList><br />
<cc1:CascadingDropDown ID="ccd1" runat="server" TargetControlID="ddl1" Category="Make"
PromptText="Please select a make" ServicePath="CarsService.asmx" ServiceMethod="GetDropDownContents">
</cc1:CascadingDropDown>
<cc1:CascadingDropDown ID="ccd2" runat="server" TargetControlID="ddl2" Category="Model"
PromptText="Please select a model" ServicePath="CarsService.asmx" ServiceMethod="GetDropDownContents"
ParentControlID="ddl1">
</cc1:CascadingDropDown>
<cc1:CascadingDropDown ID="ccd3" runat="server" TargetControlID="ddl3" Category="Color"
PromptText="Please select a color" ServicePath="CarsService.asmx" ServiceMethod="GetDropDownContents"
ParentControlID="ddl2">
</cc1:CascadingDropDown>
<asp:Button ID="btnClick" runat="server" Text="I want this car." Width="282px" OnClick="btnClick_Click" /><br />
<br />
<asp:Label ID="lblInformation" runat="server" Text="[ No sellection made yet. ]"
Width="279px"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel> </div>
</form>
</body>
</html>

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;
using System.Web.Services;
using System.Web.Services.Protocols;

namespace CascadingDropDownDemo
{
public partial class _Default : System.Web.UI.Page
{


protected void Page_Load(object sender, EventArgs e)
{

}

protected void btnClick_Click(object sender, EventArgs e)
{
// Get selected values
string make = ddl1.SelectedItem.Text;
string model = ddl2.SelectedItem.Text;
string color = ddl3.SelectedItem.Text;

// Output result string based on which values are specified
if (string.IsNullOrEmpty(make))
{
lblInformation.Text = "Please select a make.";
}
else if (string.IsNullOrEmpty(model))
{
lblInformation.Text = "Please select a model.";
}
else if (string.IsNullOrEmpty(color))
{
lblInformation.Text = "Please select a color.";
}
else
{
lblInformation.Text = string.Format("You have chosen a {0} {1} {2}. Nice car!", color, make, model);
}
}

[WebMethod]
[System.Web.Script.Services.ScriptMethod()]
public static AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownContentsPageMethod(string knownCategoryValues, string Category)
{
CarsService cs = new CarsService();
return cs.GetDropDownContents(knownCategoryValues, Category);
}

protected void ddl3_SelectedIndexChanged(object sender, EventArgs e)
{
string make = ddl1.SelectedItem.Text;
string model = ddl2.SelectedItem.Text;
string color = ddl3.SelectedItem.Text;

// Output result string based on which values are specified
if (string.IsNullOrEmpty(make))
{
lblInformation.Text = "Please select a make.";
}
else if (string.IsNullOrEmpty(model))
{
lblInformation.Text = "Please select a model.";
}
else if (string.IsNullOrEmpty(color))
{
lblInformation.Text = "Please select a color.";
}
else
{
lblInformation.Text = string.Format("You have chosen a {0} {1} {2}. Nice car!", color, make, model);
}
}
}
}

web services code

using System;
using System.Web;
using System.Collections;
using System.Collections.Specialized;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;

using AjaxControlToolkit.Design;
namespace CascadingDropDownDemo
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class CarsService : System.Web.Services.WebService
{
// Member variables
private static XmlDocument _document;
private static object _lock = new object();


// we make these public statics just so we can call them from externally for the
// page method call
//
public static XmlDocument Document
{
get
{
lock (_lock)
{
if (_document == null)
{
// Read XML data from disk
_document = new XmlDocument();
_document.Load(HttpContext.Current.Server.MapPath("~/CarsService.xml"));
}
}
return _document;
}
}

public static string[] Hierarchy
{
get
{

return new string[] { "make", "model" };
}
}

/// <summary>
/// Constructor to initialize members
/// </summary>
public CarsService()
{
}


/// <summary>
/// Helper web service method
/// </summary>
/// <param name="knownCategoryValues">private storage format string</param>
/// <param name="category">category of DropDownList to populate</param>
/// <returns>list of content items</returns>
[WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownContents(string knownCategoryValues, string category)
{
// Get a dictionary of known category/value pairs
StringDictionary knownCategoryValuesDictionary = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

// Perform a simple query against the data document
return AjaxControlToolkit.CascadingDropDown.QuerySimpleCascadingDropDownDocument(Document, Hierarchy, knownCategoryValuesDictionary, category);
}
}

}

Good luck


Hi MIB426,

Thanks heaps for your code...I am pretty new to both .NET & AJAX so I need to be a pain and ask a couple more questions.

Where can I get the web.config file from?

This part of your code (web services code) where am I meant to add this to?

Thanks heaps for your help!

using System;
using System.Web;
using System.Collections;
using System.Collections.Specialized;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;

using AjaxControlToolkit.Design;
namespace CascadingDropDownDemo
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class CarsService : System.Web.Services.WebService
{
// Member variables
private static XmlDocument _document;
private static object _lock = new object();


// we make these public statics just so we can call them from externally for the
// page method call
//
public static XmlDocument Document
{
get
{
lock (_lock)
{
if (_document == null)
{
// Read XML data from disk
_document = new XmlDocument();
_document.Load(HttpContext.Current.Server.MapPath("~/CarsService.xml"));
}
}
return _document;
}
}

public static string[] Hierarchy
{
get
{

return new string[] { "make", "model" };
}
}

/// <summary>
/// Constructor to initialize members
/// </summary>
public CarsService()
{
}


/// <summary>
/// Helper web service method
/// </summary>
/// <param name="knownCategoryValues">private storage format string</param>
/// <param name="category">category of DropDownList to populate</param>
/// <returns>list of content items</returns>
[WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownContents(string knownCategoryValues, string category)
{
// Get a dictionary of known category/value pairs
StringDictionary knownCategoryValuesDictionary = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

// Perform a simple query against the data document
return AjaxControlToolkit.CascadingDropDown.QuerySimpleCascadingDropDownDocument(Document, Hierarchy, knownCategoryValuesDictionary, category);
}
}

}


Sorry its me again.

Ok I have created a new page called default2.aspx and added the above code. I created a new web service "WebService" and added the above code into WebService.cs.

When I try run the the form I get an error saying "Error 29 Could not create type 'WebService'. C:\Users\shane\Desktop\AJAXEnabledWebSite4\WebService.asmx 1"

What else do I need to change.....Please help!!!!!!!

Thank you

Error1Could not load file or assembly Microsoft.Web.Preview or one of its dependencies. Th

Trying to run the samples and this is the error I get. After looking around I see others have gotten this error but with the beta versions.

My install is not a beta release and I have not had any of the betas installed.

Any ideas?

I would look to your web config file or possibly your machine config file. Im betting you somehow got some old beta settings in it. possibly do a search for Microsoft.Web.Preview in your entire solution.

AjaxButter


The other thing i just noticed is you said you were running the samples. Im betting your using an old compilation of the sample files that was meant to use the beta version redownload the sample your using and give it another go.

Sorry for the double post

AjaxButter


Hi,

If you have installed the AJAX Extensions 1.0, the assembly Microsoft.Web.Preview not exists.

You must to replace all the references and assemblies in the samples for run this.

Hope this helps


Replace with what?

How the Microsoft.Web.Preview not exists with the AJAX extension 1.0, you must to work with the System.Web.Extensions assembly and System.Web.Extensions.Design assembly, installed in the Microsoft ASP.NET folder in Program Files folder.

Replace the web.config with the web.config that is generated in a new ASP.NET AJAX Enabled Web Site.

Or replace your web.config with the web.config file that is in the Microsoft ASP.NET folder.



From InstallationInstructions.txt:

Completing the Installation
--------
After downloading and uncompressing the sample files, copy Microsoft.Web.Preview.dll from the
ASP.NET AJAX CTP installation directory (%Program Files%\Microsoft ASP.NET\ASP.NET 2.0 AJAX
Futures January CTP\v1.0.61025\) to the Bin directory of each sample application. For example,
copy Microsoft.Web.Preview.dll to <installation path>\Contacts\Bin, where <installation path>
is the file path where the ASP.NET AJAX Samples were installed.

You must also copy AjaxControlToolkit.dll from the AJAX Control Toolkit directory to the Bin
directory of each sample application. For example, copy <toolkit installation path>
\AjaxControlToolkit\SampleWebSite\Bin\AjaxControlToolkit.dll to <installation path>\Contacts\Bin,
where <toolkit installation path> is the installation path for the AJAX Control Toolkit and
<installation path> is the file path where the ASP.NET AJAX Samples were installed.

Earlier in InstallationInstructions.txt are the download locations for the Futures CTP and the Control Toolkit.