ASP.NET Script after partial postback - asp.net

I have a web page to modify a script that show the weather info of a certain city.
In this page, users can change the city by loading a different script. This script is copied from a weather site, as a widget.
I have this line to show the weather:
<asp:Literal ID="ltWeatherScript" runat="server" Text='<%# Eval("WeatherScript") %>'>
</asp:Literal>
Where "WeatherScript" is the script that shows the weather.
The problem is when the page has a partial postback, the script doesn't work anymore until I reload the page.
The script could be, for example, this one:
script type="text/javascript" src="http://tiempo.meteored.com/wid_loader/50a0f88ef4aae65daacf31e7a4b1b0fe"
Do you know how to solve this?

I did checked the JS.
this lines are the only suspects to cause problem.
conte = document.getElementById('cont_50a0f88ef4aae65daacf31e7a4b1b0fe');
enlace = document.getElementById('h_50a0f88ef4aae65daacf31e7a4b1b0fe');
anchor = document.getElementById('a_50a0f88ef4aae65daacf31e7a4b1b0fe');
And you said The problem is when the page has a partial postback, the script doesn't work anymore. So the reason maybe that after postback control's IDs are changing. if you can post a markup that will help to diagnose the problem. as for solution, you have to specify the ClientId of the control. check the link Control.ClientID Property to get more info about this property and how to use it.

You need to get the script you're loading (WeatherScript) to execute again after a partial postback. Since the script is not a function, you'll need to create a function on the page that does the (shivers in horror) eval of the script you've loaded from their website. Then you'll need to invoke that function on page load and partial update.
What method are you using for partial postbacks? Update panels, jQuery/XUI AJAX call, etc? This will help me show you the code you need to add to invoke your new function when the partial postback completes.

Related

Failed to load viewstate. The control tree into which viewstate is being loaded

I am receiving the following error message after an HTTP POST on an ASP.NET form hosted inside a UserControl:
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.
Here's additional info:
I'm running .NET 4.5 RC
It's an Umbraco 4.7-based website
On my local dev machine the form works perfectly
This error only occurs on the staging server which has .NET 4.5 (only), MSSQL 2012 Express, IIS 7.5, Windows 7 (I know, it's not a real server yet, one day maybe...)
The server is not part of a web farm (or garden, tho that should be irrevelant)
The user control does render controls dynamically
I have applied all the latest service packs.
I have run out of ideas now! I have even restarted it and also performed a richual over the server involving a song and a special dance to no avail.
What is important when you are adding controls dynamically is on which event you are adding them.
If you added controls on events that occur after load, they will be part of the viewstate you send to the client.
You will have to add those controls again before LoadViewState is called.
If you run into cases where the decision of which controls to add is itself stored in the ViewState or the value of a control, then remember even before the ViewState is loaded, this data is available in Request.Params
Refer the asp.net page life cycle
I just added EnableViewState="false" to my page placeholder and its gone. Hope it works for u as well.
This Error Mainly Occurs during View state Change: From One Template To other Template like in case of Item Template, Edit Item Template, in Controls like Form View, List Views, Detail View, Grid View in ASP .net (all frameworks);
While Changing from control states say Item Template ---> Edit Template
the followings were going to alter
1) Controls will change (its ID & states)
2) Its Positions will change.
While Transformation of view if any post back occurs you will get Error as
Failed to load viewstate. The control tree into which viewstate is
being loaded....
if you are using separate control for data-binding like (button,link_button_Image_button events) you will get this error reported !
To avoid this error >>> Once state changes from one template to other within method you call data source binding ( Don't call during click or any post backing events ).
OK, so the answer is literally: "Set up a new server with all the same software as the last one and try again" and it works now.
I add "name" attribute with the same value as id, then this problem is gone.
<input type="button" id="extractBomInfoBtn" name="extractBomInfoBtn" value="Extract" class="button textonly" />
I had the same issue. This issue was at client end but it didn't occur in my local system.
After hours of googling, i had written EnableViewState="false" to my table tag in aspx page which has all the dynamic controls and then i removed all the viewstate variables and instead i created some hidden textboxes in the aspx page and accepted DB values into them in code behind and used them throughout my code. It then solved my problem.
But still, i couldn't figure out what was exactly the problem.
In my case I was manipulating the .Text property of a asp:Literal on page load which was causing the issue. In all other cases this never caused me a viewstate error but in this particular case I was changing the .Text value to an html element.
The following caused the error:
<asp:Literal ID="SvgIcon" runat="server" />
SvgIcon.Text = "<svg version=\"1.1\" id=\"Layer_1\" bla bla />"
I was able to resolve the error by adding EnableViewState="false" explicitly to the control:
<asp:Literal ID="SvgIcon" runat="server" EnableViewState="false" />
Check if you have the binding method of the control directly in your page load event. This can cause this problem.
You can add new PlaceHolder per UserControls
OR
You can set enableviewstate=false on the control , if you dont need viewstate
In my case I had a grid view with (OnPageIndexChanging) event
and when I click on a page nothing will happen until I click it twice!
I was refreshing the data source before setting new page index.
This is what I was doing wrong
grd.DataSource = data;
grd.DataBind();
grd.PageIndex = e.NewPageIndex;
This is the right way
grd.PageIndex = e.NewPageIndex;
grd.DataSource = data;
grd.DataBind();
This can happen if you override SaveViewState in your control but don't override LoadViewState.
So I actually ended up discovering that the list of entities I was binding to was not in the same order as the controls in ViewState! I'm still working thru a cleaner solution, but my code is working with ViewStateEnabled = true by having the method which reconstructs my dynamic controls (called from Page_Load) do it differently if !IsPostBack.
Ultimately, I will probably need to fix my sorting algorithm for my nested dynamic controls, but suffice it to say: if you are using the same pattern as I am, of using a List to generate/bind to dynamic controls, and that order is fluid or changing, try comparing Request.Params to find the keys that are relevant to your control hierarchy, and see if they match the order of your List. That solved my issue. Kudos to #nunespascal!
In short, I am dynamically generating all but one tab in an AjaxToolkit tab control, and then populating that with a couple layers deep of placeholders and regular controls (textboxes, dropdownlists, etc), so that's why it's complicated to get the order of everything correct.
Although this is very old question, I had visited this as I got the similar issue. But my issue was generated just because I have added a javascript code in Master page in head tag. That javascript code is reading a value of Session["KeyName"] ,
Code is like below -
$(document).ready(function () {
var allowOpenInNewTab = false;
allowOpenInNewTab = '<%# Convert.ToString(Session["AllowOpenInNewTab"]).ToLower() %>' == 'true';
if (!allowOpenInNewTab && window.sessionStorage.tabId != '1') {
alert("This page is not allowed to be open in another tab, sorry we can not load the page!!");
}
});
When I remove above code then everything was running smoothly but if I keep adding this part of code, it was giving this error of
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate...
Finally I found the solution like if I move my javascript code from head to just before the end of the body tag.
So solution that worked for me was moving javascript code (which is reading Session value from Server tags) to just before end of body tag.

How can I trigger the OnCheckedChanged-Event?

My webpart is programmed with C# and shall show a form and a checkbox. If the user click on it the OnCheckedChanged-Event must trigger (I think so). But the webpart send the dates not at this time to server. With <asp:checkbox ... AutoPostBack = "true" ... /> it works. The problem is that the other form fields are thereby extinguished/reset and I donĀ“t want cache the data. What can I do? It is reasonable evaluate the checkbox on client-site? Or can I trigger the OnCheckedChanged-Event by an other way?
thanks.
I think this is occurring because of postback . You must check the Ispostback property on page load in order to avoid this type of issues.
Also this helps you to prevent unwanted function calls when you do postback. Also check the function you are calling in page load.
Also there is a chance that you may set ViewState="false" in html part. So that the controls doesn't have any value after the postback. Make sure that you are enabling the ViewState for your controls.
Just have a look at these urls. or paste you html as well as Code in Page Load event .
Kindly provide some more details.

.aspx works but .ascx does not... why and how to fix?

I want to put a ASTreeView web control in a custom web control, ASTreeView sample code is like:
<ct:ASTreeView ID="astvMyTree"
runat="server"
...
LoadNodesProvider="~/ASTreeViewDemo5.aspx"
.../>
LoadNodesProvider is the page ajax called when loading a node...however if I changed the provider to my .ascx file, it does not work:
LoadNodesProvider="~/ASTreeViewDemo5.ascx"
it did not even go through the Page_Load part of the .ascx file
Though this might be related with astreeview itself, I'm wondering what the problem could be? anything I can do to fix it?
Thanks!
It is because ascx must have a container ie Page. You can't use it same way as Page.
ASPX is a page and ASCX is a usercontrol. You cannot ajax call a control, so you probably want it to be a page with the control on it.
While it isnt entirely clear to me what LoadNodesProvider is supposed to do, if you want to encapsulate some code or run a process via AJAX you have a couple of options. One would be to create a web service (you could use WCF for this) that the AJAX method could call. Another option would be to create an http handler (ASHX extension typically denotes this). Using an ASPX or ASCX for this doesn't make a whole lot of sense to me. Proco and Tomas are correct regarding the ASCX file, these are Usercontrols and are not stand-alone objects.
If you really, really want to use an ASPX page/ASCX control, then I suppose it would be best to create a blank ASPX page that has one placeholder, and then attach your user control (based on query string parameters or something I guess) to the placeholder to render out the content for your AJAX control

How do I temporarily convert an ASP.NET Ajax form to not use partial page updates?

I need the ability to temporarily turn off the partial page update behavior for an ASP.NET Ajax / UpdatePanel based page. (The reason is to circumvent the issue where IE blocks "automatic file downloads" for downloads generated as a result of this postback, but I don't want to distract from my original question)
I looked at the client side javascript libraries hoping to find a switch somewhere. I think a solution might involve using javascript to override the 'onclick' event handler for the control that acts as the trigger, and then calling "submit" on the form itself..
Also, using the EnablePartialRendering property on the server-side ScriptManager control won't work because that is done when the page is being built. I need to be able to do this as a result of switching a drop down list box.
Any ideas?
Cheers!
/ Sean
Well, after much trial and error, I found two approaches that seemed to work:
Use Javascript to manually submit the top level form associated with the page. This usually has the ID of "form1".
Create a button that is outside of any UpdatePanels and use Javascript to click the button.
I wound up using the second approach, since it allowed me to handle the event with a specific routine without the need to guess that my postback came from a Javascript call.
This is an example of the code that performed the postback:
...
if (isDownload) {
document.getElementById('FullPostbackSubmitter').click();
return;
}
...
Hope this helps someone else!
You can set the EnablePartialRendering property of your ScriptManager to false.

Javascript: Referring to control before page is loaded

I have a composite control on an ASPX page. There is Javascript on the ASPX page that gets loaded before the control. Now, since the script refers to the control element which does not exist when the script is loaded, this is throwing a Javascript error of "Obect not defined". Attaching the script to the onload event of the control gives "Sys not defined".
Any Idea?
The script is in an external file.
You need to either move the Javascript function below the control creation, or add it inside a window.load event handler (jQuery and Prototype can help you for that), so you guarantee that the Javascript is called when the page has loaded and not before.
You can keep the script in the load method of your control, although really it should be placed in the PreRender because then you can include it or not include it based on the state of the control. This would save you from javascript errors in the future where it says "Object cannot be found" because you have made the control invisible.
The reason you're getting "Sys is not defined" is because your script is being placed before the MicrosoftAjax.js file has loaded. Try something like this:
Dim yourScript as String = "Sys.Application.add_load(function() { /*code here*/ } )"
ScriptManager.RegisterStartupScript(Page, Me.GetType(), "ScriptKey", yourScript, true)
Otherwise you could use Page.ClientScript to hook into the document ready event if using the Sys namespace is not a requirement, but it sounds like from your question it is.
Edit:
Instead of RegisterStartupScript you're probably looking for RegisterClientScriptBlock, sorry, the two have different functionality.

Resources