I'm having a problem with a very normal ASP.NET dropdownlist.
I have a dropdownlist in the page with AutoPostback=false.
And a code to generate dropdownlist’s content:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.dropDownList.Items.Add(new ListItem("text1", "value1"));
this.dropDownList.Items.Add(new ListItem("text2", "value2"));
this.dropDownList.SelectedIndex = 0;
}
}
Run the page, and choose the second option: text2.
After that, press F5, this will do a page load (note that I haven't done any postback yet, just change the selected item of Dropdownlist and press F5)
I expected that the dropdownlist will now selected the default item with index = 0, but the selected item is still the item “text2”- the item that I have chosen. In this situation, the this.dropDownList.SelectedIndex = 0; doesn’t work.
I totally don’t understand. Could anyone help me?
Update: This behavior only happens in Firefox, it doesn't happen in Chrome/IE.
It seems like you're misunderstanding what post back means; it does not mean just a page refresh. When you hit F5 in the browser, the original request will be sent to the server, and Page.IsPostBack will be false.
If you want to do an actual postback, add an asp:Button server control to the page and click it (or just set AutoPostBack=true on the DropDownList).
It seems like Firefox is doing some kind of client-side caching, so it doesn't make another round-trip to the server when you hit F5. You can work around this by resetting the select element when the page loads.
<script type='text/javascript'>
document.getElementById('<%= dropDownList.ClientID %>').selectedIndex = 0;
</script>
(Note: put this at the bottom of the page so that it executes after the document has loaded.)
When you press F5, it will send the post headers along with the request.
Your last request was to select the second option. So that gets selected.
If you type the url again, or hit enter in the address bar; you will not send the post data.
In this case your SelectedIndex will be 0.
Related
I am working on web application. I have a grid that shows data to the user. When user click on the any row of the grid, it redirects user to another page, as we have a asp link control on the a column.
Issues
My code is like
if (!Page.IsPostBack)
{
//CODE
}
When user click on the BROWSER BACK button, it does not execute the CODE. Simply show the data from CACHE.
How can I execute the CODE , on browser back button click ?
It's a global problem with ASP.Net. Most of developers thinks like Windows developer. It ends with a postback for mostly any action, including navigation actions.
To solve such problems:
Avoid using button to change page. Generate an hyperlink with the target url.
Wrap parts of the page within an update panel. The benefits is that the browser won't see a page change after each postback. Then you will be able to "refresh" the page without warning dialog
When populating a grid, instead of "selecting" a row from codebehin, generate a link to the same page with "?ID=42" in the url, and bind this value to the grid as the selectedvalue
The root cause of this "evil" behavior, is that postback are issued using HTTP Post request. Then, the browser requires to repost the page to rebuild it.
Using the technics mentionned above, you are issuing GET request. This kind of request doesn't require to resubmit anything.
Try Disabling browser cache for the page that you don't want to cache.
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
if (!Page.IsPostBack)
{
//CODE
}
}
I have a textbox in my default.aspx page that I want to update it's text property in an event handler but the change does not take place after executing the code .
void _gsc_Task_Completed(object sender, TaskEventArgs e)
{
TextBox1.Text = "New Value";
}
How ever , if I do this on the click event of a simple button the textbox.Text value
changes.
what is the difference between a custom event handler like _gsc_Task_Completed and a simple button click event ?
Text box is a server side control. when you change the text this work(change text) is client side so the event not firing. but when i click on a button the page is going to server and back so the event is firing.
You need to consider the page lifecycle: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx
Either your event handler is being called to early (and clobbered by whatever is brought back from the client) or it is being called after the control was already rendered.
If I were you I'd put a breakpoint there as well as normal handlers for page onInit, onLoad, etc. See what order that handler is called (if at all) and what is below it on the callstack.
In an effort to speed up my site, I am trying to disable the viewstate as I don't think I am using it everywhere. I have a master page setup with user controls loaded (using LoadControl) in default.aspx. My typical page setup would be:
Main.master -> Default.aspx -> ControlWrapper.ascx -> MyControl.ascx
I have put EnableViewState="false" in my Default.aspx page. Now when I try and read a value from a DropDownList in MyControl.ascx it comes back blank when the form is posted. First all, why is this? I thought I should still be able to read the value from the drop down list?
I then tried enabling the ViewState on that control and it didn't work.
I also tried enabling the viewstate on the Page_Init event of MyControl.ascx using Page.EnableViewState = True; but that didn't help either.
I guess I am misunderstanding the viewstate somewhat, can someone point me in the right direction please?
p.s I don't know if this information is relevant but I am adding the contents of the DropDownList dynamically in the Page_Load event. (Thinking about it, could this be the issues - Will test this now).
Thanks.
With viewstate turned off, the values you are loading in Page_Load are no longer in the list when you post back (until you reload them obviously). If you want to work without viewstate, you will need to set the selected item from the value in Request.Form.
protected void Page_Load(object sender, System.EventArgs e)
{
ddlItems.Items.Add(new ListItem("test1", "test1"));
ddlItems.Items.Add(new ListItem("test2", "test2"));
ddlItems.Items.Add(new ListItem("test3", "test3"));
if (Page.IsPostBack)
ddlItems.SelectedValue = Request.Form["ddlItems"];
}
When you've set ViewState to false the dropdown needs to get populated before page load - which means you probably should do it at page init. Something like this:
protected void Page_Init(object sender, System.EventArgs e)
{
ddlItems.Items.Add(new ListItem("test1", "test1"));
ddlItems.Items.Add(new ListItem("test2", "test2"));
ddlItems.Items.Add(new ListItem("test3", "test3"));
}
Then you should be able to read the value at load:
protected void Page_Load(object sender, System.EventArgs e)
{
someTextBox = ddlItems.SelectedValue;
}
A bit of background:
On this page: Microsofts page cycle
At the image with the page cycle there is the methods "ProcessPostData" and "LoadPostData" firing in between Init and Load. The post data for the drop down contains the selected value - but not the possible values, so when it loads the post data it is essential that the possible values are already there (or it won't be able to set the selected value). Also before the post data has been loaded the selected value has not been set.
If viewstate is enabled it saves and retrieves the possible values in between postbacks.
I will assume you're using .NET 4. View State is the method that the ASP.NET page framework uses to preserve page and control values between round trips.
The reason it didn't work for you when View State was turned off is because that control was rendered again when you performed a PostBack to the server, meaning you lost your selected value.
The reason it didn't work for you when View State was off for the page, but on for the control is because in order for that to work, the following conditions must be met:
The EnableViewState property for the page is set to true.
The EnableViewState property for the control is set to true.
The ViewStateMode property for the control is set to Enabled or inherits the Enabled setting.
ASP .NET View State Overview
When you did EnableViewState = false; on a page then you should not expect DropdownList.SelectedValue after postback.
It will be good if you Enable/Disable ViewState on particular controls rather than disabling whole view state by specifying it on page directive.
Is this possible?
EDIT
I want to user the asp:ListView
List item
I want to use it for editing
I dont want the postback to use Javascript when I put it into the edit mode
I've been trying to use a to do this instead of a link button but to no avail.
.
The only way to trigger a PostBack without JavaScript is by using a submit button. This is an HTML limitation, not an ASP.NET one.
I'm a little unsure of what you're trying to do without more detail. If I knew more specifically what you're trying to accomplish I could give you more details.
Like you mentioned in your post, you could use the <a> tag to send the user to the page you want.
You can add information to the link like so:
Click here for a new item
Then in the page load of newpage.aspx you can check what the action the user selected was, the query parameters are stored in the Request (Language is C#).
protected void Page_Load(object sender, EventArgs e)
{
string action = Request.Params["action"];
if(!String.IsNullOrEmpty(action))
{
switch(action)
{
case "newitem":
//handle the new item action
break;
case "deleteitem":
//handle the delete item action
break;
//handle other actions.
}
}
}
EDIT: You should be aware that the <a> tag will send the user to the page specified, the page though will act as if it is the first time the user has visited the page. With that said, the page variable IsPostBack will be false.
I have command button added in my asp.net grids. After performing an action using that button, we refresh the grid to reflect the new data. (basically this action duplicates the grid row).
Now when user refresh the page using F5, an alert message is displayed (to resend the information to server) if we select "retry", the action is repeated automatically.
I know this is a common problem in asp.net, how can we best handle this?
Search for GET after POST - http://en.wikipedia.org/wiki/Post/Redirect/Get - basically, redirect to the current page after you're finished processing your event.
Something like:
Response.Redirect(Request.RawUrl)
If you think you don't need postback paradigm, you might want to look at ASP.NET MVC.
The problem is that asp.net buttons perform form posts when you push a button. If you replace the button with a link your problem should go away. You can also use a button that performs a javascript function that sets the document.location to the address of your page.
If I well understood, you simply have to check if you are in a post-back situation before populating your grid.
Assuming you do that on Page_Load, simply surround the operation with post-back test like this:
private void Page_Load(object sender, EventArgs e)
{
if(!this.IsPostBack)
{
// populate grid
}
}
You need to call response.Redirect(Request.Url.ToString());
or you can wrap the grid with updatepanel and after every command bind the datasource to grid
Inside your <asp:Repeater> tag put this:
EnableViewState="false"
This will cause your control to refresh every time the page loads, no matter if it's a postback or not.
for example:
if you click on 'button' system will catch the event 'button_click'.
if you refresh the page, system will re execute again the same event.
to don t have this problem, in your event insert :
on your event
private void button_click(object sender, System.EventArgs e)
{
button.Enabled =false;
button.Enabled =true;
}
is what you meant?