IsPostBack property of the page never gets false even after page refresh - c#

I get stuck in a very unusual problem. I've a code written in C# which is simply checking IsPostBack property on the Page_Load. I know that IsPostBack remains false when page lands for the first time and bocme true only when any control post the form to the server (having runat=sever).
I also know that if we hit refresh, the IsPostBack property should change to false (since refresh is not a postback).
This is the sample code:
if (!IsPostBack)
{
// If I click on any control on the page, and then hit refresh,
// the code inside this block should execute, but this is not happening.
// After first postback, I tried refreshing the page for more than
// ten times, but always finds IsPostBack=true
// ...
}
else
{
// ...
}
I clicked on a server side button (a postback), then hit refresh. I assume it will go to the if block but no luck. No matter how many times i hit Refresh on browser, IsPostBack is always true. which is truly an unusual activity I've never seen before.
I would really appreciate any help. I need to know why this is happening, is this a browser related problem or something else? I used mozilla and chrome.
Every time I hit refresh, I get a warning on both browsers.
On chrome: Confirm form submission
The page that you're looking for used info that you entered, returning to that page might cause any action you took to be repeated.Do you want to continue?
On mozilla: Confirm
To display the page, firefox must send info that will repeat any action...
Thanks in advance for any kind help.
Praveen

Most browser will do a post of the same data if you refresh after posting.
This is the meaning of the dialogues you have seen (they are asking if you want to re-post - click yes/OK means a re-post).
In order to avoid the re-post, simply go to the address bar and press enter. That will cause a new request to be issues rather than a re-post.

Those dialogs that the browsers put up tell you that they are going to do a postback instead of just get'ting the page. And you can see in your code that the warnings are accurate - any handlers that were invoked on the original postback will get invoked a second time. This is one of the main problems with postbacks - they essentially break the refresh key. If you just want to load the page, you have to mouse up to the address bar and hit enter. This will load the page with IsPostback false.

Related

Response.redirect execute the code inside the pageload twice

I have this link http://localhost:54818/offerslinks/offers.aspx?ID=1 when i clicked it. it loads the page and executes this code twice
enter image description here
this code execute twice
can any one help me with that ?
You might have to share how webform1 is calling the web page that you response.redirect to (maybe the same page???).
You have a isPostBack check, and note that page load ALWAYS will trigger again, and each time for each button click (post-back) on that given page. So, if you have a simple button on that that webform1, click on it, the page-load event will fire again, and THEN your button code stub will then run.
Of course with a is-postback = false test, then ONLY on first page load should that code run runside that if !PostBack.
However, the code WILL run again if your response.redirect points to the same page. If you have in that same page, a response.redirect to the SAME page, then not only will page load trigger again, so will the code inside of !IsPostBack code stub.
So, we need more details, or more markup to be posted here (and post the markup in place of screen shots - screen shots are a pain to read, but WORSE is I will often cut + paste markup into a test page while answering questions here - I can't do that if you post image(s), since then I would have to take away time from my life and family, and re-type such markup (or code) to test such things for you when answering questions here.
My best guess is that the response-redirect points to the same page. Thus upon that code running, it re-directs to the same page, and that would thus cause the page load to run again, and also cause isPostBack to be false, which then means the code isside that stub will also run again.
So, missing from this information is how/when/where that page is being loaded - without those details, we are in effect throwing darts in a room with the lights out.

WebBroswer_DocumentCompleted event is not working

I have a form with a browser control. (this control uses IE9 because I set values on registry editor)
This web browser navigates to a specific URL and fills all fields on HTML page and submit them, then result page is displayed.
My problem is that i just want to know when this reslut page is fully loaded or completed so that i can fetch some information.
I use WebBroswer_DocumentCompleted event which works fine for the first page but not for the result page as it triggers before result
page is loaded.
I tried other solution which is to check the div tag inside the result page (this tag only appears when result page is loaded completely) and it works but not always.
My code:
private void WebBroswer_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HtmlElementCollection elc3 = this.BotBrowser.Document.GetElementsByTagName("div");
foreach (HtmlElement el in elc3)
{
if (el.GetAttribute("id").Equals("Summary_Views")) //this determine i am at the result page
{
// fetch the result
}
}}
That div id is "Summary_Views".
I can provide you the link of that website on demand which is just for BLAST tools and database website for research purpose.
Frames and IFrames will cause this event to fire multiple times. Check out this answer:
HTML - How do I know when all frames are loaded?
Or this answer:
How to use WebBrowser control DocumentCompleted event in C#?
Or ms's kb article:
http://support.microsoft.com/kb/180366
Do you know if there are frames? If so then please say so, so people can help with that. If not then say so, so people can offer alternatives.
My guess is that the content is being generated by JavaScript. If it is then the document is complete before the JavaScript executes and you need to somehow wait until the JavaScript is done. The solution depends upon the web page. So you might need to process multiple document completes for diagnostic purposes and attempt to determine if there is a way to know which one you need.
At last i have solved my problem. I put a timer control from toolbox and set its time interval to 200ms and its Autoreset property to false. I set a tick event which has a code to check every 200ms whether this Div has been loaded or not, after that, Autoreset property is set to true.This solution is working perfectly :)

WebBrowser and javascript

I am working with a website that has javascript that does some changes on the page load. However, when I load the page and handle the DocumentCompleted event, this change isn't there. If I then continue paste the DocumentCompleted event, I can see the change happen. However I need this change to happen during DocumentCompleted so I can check some things.
Is there an other event I can subscribe to, or a way to cause the webBrowser to do all the javscript on page?
Edit: This is what I am talking about.
I loaded a sample page just to show you, and clicked the submit button with all fields empty to generate an the error.
Here is the result:
http://s8.postimage.org/zfv6stcar/sfsdfsdfds.jpg
Now if I take the HTML at that precise moment from that WebBrowser control, and render it somewhere else, those errors go away. The same thing happens when the server sends back those errors. If I handle the DocumentCompleted event and take the html, it isnt there. But after the event, it shows up in the control.
Hope you understand, it's hard to explain.
The problem seems to be that the DocumentCompleted event is being fired before the javascript. You should do some reading on how client side/server side things function.
One option is to make a separate method for the DocumentCompleted event and call it form the javascript after it has been completed. This would get the sequencing of these events working properly, but is not very ideal.
Alternatively, you could call the javascript code at the beginning of your DocumentCompleted event. The link below gives a pretty good explanation of how to go about that.
http://forums.asp.net/t/1117189.aspx/1
Personally, I would avoid using javascript and do the validation on the client side .NET, but I don't know enough about the website to really say.
EDIT:
This should be the script you are looking for. Alternatively here is a thread related to your issue. Sorry I don't have the exact code as I don't have a project to test this on.
http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx
Calling JavaScript Function From CodeBehind
RE-EDIT:
What is happening on the link you provided in the comments, is that each textbox is calling some javascript as well as the submit button. The best way to examine this is using the "Inspect Element" in the right-click menu on Google Chrome. For example, doing this on the textbox would show that it is registered with a few events:
onfocus="$('f_tip_Username').style.display = 'inline'"
onblur="$('f_tip_Username').style.display = 'none'"
onchange="$('f_err_Username').style.display = 'none'"
The first the element with the ID 'f_tip_Username', sets the display style of that element to inline (visible).
The submit button calls the following:
onclick="return o_edit_profile_form.validate()"
Doing a find on "o_edit_profile_form" in the source code, you can find the exact javascript location that is being called. Enjoy!
FINAL EDIT (hopefully?):
Follow these steps: go to your site, right click and go view source. Do a find for "f_tip_Username". This is the ID of one of the div tags being used. The third entry of it, should be a "div tag" that is used under the first textbox to warn of "min 3 characters".
You'll notice above that in the code is a input type "text" with the Name "Username". Notice the three events it has registered in it:
onfocus="$('f_tip_Username').style.display = 'inline'"
onblur="$('f_tip_Username').style.display = 'none'"
onchange="$('f_err_Username').style.display = 'none'"
These either hide or make visible, the div tag we found (f_tip_username) and also a separate div tag (f_err_Username) which is the error message div tag. Let me know if you are not able to find these in the source. Follow the steps I provided and you will find it in the "view source" OR in the DocumentText.

Unable to get updated value of session variable and Textbox

I am building a web application in asp.net and c#, I am storing text of textbox in Session variable like this:
Session["data"]=TextBox1.Text;
and on the button click event I am redirecting user to another page.In the second page I am using this variable Session["data"] and in page2 there is a back button where I am again Redirecting to page1 where the textbox1 is present.Now on the button click event where I am redirecting to page2 and event is code like this,
Session["data"]=TextBox1.Text;
Response.Redirect("page2.aspx");
now when I am accessing the value of the Session["data"] it is giving me the previous value.As the content of TextBox1 may get changed,these changes have not been shown.
Please tell me where I am going wrong.
I dont think the code you are using is worng. You please make a break point and check it again that the values are assigning correctly
Or
You just set the session to null and then assign the textbox value to it on the click event.
Read this I think Respone.Redirect might be causing you to lose your session data
Don't redirect after setting a Session variable (or do it right)
A problem I see over and over again on the ASP.NET forums is the
following: In a login page, if the user and password have been
validated, the page developer wants to redirect to the default page.
To do this, he writes the following code:
Session["Login"] = true;
Response.Redirect("~/default.aspx");
Well, this doesn't work. Can you
see why? Yes, it's because of the way Redirect and session variables
work. When you create a new session (that is, the first time you write
to a Session variable), ASP.NET sets a volatile cookie on the client
that contains the session token. On all subsequent requests, and as
long as the server session and the client cookie have not expired,
ASP.NET can look at this cookie and find the right session. Now, what
Redirect does is to send a special header to the client so that it
asks the server for a different page than the one it was waiting for.
Server-side, after sending this header, Redirect ends the response.
This is a very violent thing to do. Response.End actually stops the
execution of the page wherever it is using a ThreadAbortException.
What happens really here is that the session token gets lost in the
battle. There are a few things you can do to solve this problem.
First, in the case of the forms authentication, we already provide a
special redirect method: FormsAuthentication.RedirectFromLoginPage.
This method is great because, well, it works, and also because it will
return the user to the page he was asking for in the first place, and
not always default. This means that the user can bookmark protected
pages on the site, among other things. Another thing you can do is use
the overloaded version of Redirect:
Response.Redirect("~/default.aspx", false);
This does not abort the
thread and thus conserve the session token. Actually, this overload is
used internally by RedirectFromLoginPage. As a matter of facts, I
would advise to always use this overloaded version over the other just
to avoid the nasty effects of the exception. The non-overloaded
version is actually here to stay syntactically compatible with classic
ASP.
I don't really see what you want to do here. You say it works (the Session["data"] contains the text of TextBox1?) but you don't see any changes? What changes did you expect? Please give us some more information about this part of the question:
As the content of TextBox1 may get changed,these changes have not been shown.
Thanks.
Update:
Try clearing or remove the session and then refill it.
Session.Remove("data");
Session.Clear();

user control event handler lost on postback

I have a menu usercontrol called LeftMenu that has a bulletedlist of linkitems. It's on the ascx page as such:
<asp:BulletedList ID="PublisherList" DisplayMode="LinkButton" OnClick="PublisherList_Click" cssClass="Menu" runat="server"></asp:BulletedList>
I databind the list in the page_load under if(!isPostBack)
I'm having an issue on a page that loads the control. When the page first loads, the event handler fires. However, when the page posts back it no longer fires and in IE8, when I'm debugging, I get "Microsoft JScript runtime error: Object expected" in Visual Studio pointing at "__doPostBack('LeftMenu$PublisherList','0')." In FF I don't get the error, but nothing happens. I'm not loading the control dynamically, it's loaded on the aspx page using:
<%# Register TagPrefix="Standards" TagName="LeftMenu" Src="LeftMenu.ascx" %>
<Standards:LeftMenu ID="LeftMenu" runat="server"/>
Any ideas of where I'm losing the event handler?
I just realized this is happening on another user control I have as well. A text box and a button and I'm using the default button to make sure pressing the enter key uses that button. .Net converts that in the html to:
<div id="SearchBarInclude_SearchBar" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'SearchBarInclude_QuickSearchButton')">
so as soon as i enter a key in the box I get a javascript error at the line saying "object expected." It seems like the two issues are related.
Edit Again: I think I need to clarify. It's not that I'm clicking on the menu item and it can't find the selected item on postback. I have this search page with the left navigation on it and then the main content of the page is something that causes a postback. Everything is fine with this postback. Once that page has been posted back, now if I click on the bulleted list in the left navigation I get a javascript error and it fails. The page_init for the LeftMenu control is never called.
It sounds like you might be losing the click because you are not DataBinding the list on PostBack. Therefore, the post back is trying to refer to a control (a specific bulleted list item) that does not exist.
You should try binding the list again on PostBack just to see if that fixes your issue. BUT, what should REALLY happen is that the LeftMenu and the BulletedList should store their information into ViewState so that you can ensure that the data that was shown to the user on their initial page load is the same data that the PostBack is processing and working with.
If you have EnableViewState=true for your UserControl and all controls within it, everything should work fine. With ViewState enabled, ASP will reinflate your controls from ViewState after Init has fired. This means that the postback event arg (which points to an index in your control list) will still find the control in that list position. Otherwise the list is empty on postback.
However, ViewState is the work of the devil and was designed simply to foster the illusion that you are working in a stateful environment. It is okay to use it for small amounts of data but typically not advisable for templated controls like repeaters and lists because you have no idea how much data is going to be created in ViewState.
If you are dealing with static, or relatively static data, store it in the application cache and rebind your lists in Page.Init every time (note that it has to be in Init because post-init is when ASP rebinds from ViewState; if you get in there first, your data will be used instead).
If you are dealing with volatile data, you have a problem because the data you rebind must be exactly the same as the original page request, otherwise the postback events will be firing against the wrong rows. In that case you need to either store your initial data in Session or you simply store the list of rows ids (in a hidden variable or Session) and you recreate the data to bind against from the ids each time.
An even better solution is to not use postback events at all. Try to turn all your events into GETs that have an ID on the query string. You can still create the list using binding the first time through the page (as you are currently doing), and you can even GET the same page with a new ID.
If you need to keep state on the same page but need to respond to the user changing a radio button selection (or something else), think about using Ajax calls to update the screen. You also do that with an ID that you pass to the Ajax call.
In general, the more you move from using stateful ASP, the lighter and more responsive your pages will become. You will also be in a better position to move to stateless MVC if necessary. You will also save lots of time lost to debugging obscure problems because ViewState is not available when you need it to be.
The best analysis of ViewState I've read is in the link below. If you fully understand how it works, you can continue to use it without necessarily incurring the costs.
http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/truly-understanding-viewstate.aspx
It's possible that this might be javascript related, and that a script that is loading earlier in the page is throwing an error and causing the page to not be loaded properly.
Are your usercontrols loading any javascript onto the page? Can you check for javascript errors on the initial load of the page?
I moved the code into an existing project we have and for some strange reason, I stopped getting the javascript errors and instead got:
"Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%# Page EnableEventValidation="true" %> in a page.
For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation."
I haven't quite figured out where I'm supposed to put the register event validation with a user control, but in the mean time I just set enableeventvalidation=false and it seems to work now.
It looks like the doPostBack function is missing since its arguments are literals so they couldn't be the cause. Is that one of your own functions or did you mean to call the ASP __doPostBack function?
Have a look at the Firefox error console or allow script debugging in IE and see exactly what object can't be found. Even better, download Firebug and debug it.
I had a similar issue. It turned out that Akamai was modifying the user-agent string because an setting was being applied that was not needed.
This meant that some .NET controls did not render __doPostBack code properly. This issue has been blogged here.

Categories