Viewstate Disabled - Dropdown box not returning values - asp.net

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.

Related

ASP.Net LifeCycle and Database Update order

I have been reading about the Page LifeCycle. I understand the LifeCycle, however, it's not clear on what to do, and when to do it. The problem is I use Page_Load to get database values, and set form fields. I use a button's onClick method to update the database. However, the form fields text properties were set during Page_Load, so it's really only updating the database with the OLD values.
Page_Load: I gather data, and set control text properties to reflect data.
Button_onClick: I update the database from the form
Problem: It's updating values gathered from Page_Load and not the actual form.
Certainly, I am not supposed to perform everything in the Page_Load. So where am I going wrong during this process?
Page_Load
If you are loading your database data in the Page_Load event, the very first thing to do is to wrap it within a if (!IsPostBack) statement.
IsPostBack
Gets a value that indicates whether the page is being rendered for the
first time or is being loaded in response to a postback.
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
So IsPostBack = true when the page cycle is the result of postback.
In your Page_Load, you should only gather your data when IsPostBack = false, not on every page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// gather your data here
}
}
Setting fields
I personnaly prefer to set the fields content on the PreRender event handler (but honnestly i don't know it should/must be done there, it just seems more logic to me).
PreRender is executed after your postback events (click on a button, drop-down selection change...) so it ensures that your updates and more generally data modifications are done before rendering the page.

Events are not working if UserControl.ascx are loaded through LoadControl(ctr)

I find this as a funny little problem. I think the reason lies behind the life-cycle of page-object/events-generation, but the question is how I come around the problem?
In Default.aspx there exist some funny controls but also a
<asp:PlaceHolder runat="server" id="phUserContent"></asp:PlaceHolder>
This placeholder is empty until runtime. Code behind are, in some circumstances, loading UserControls into it. Like this
Control ctr = LoadControl("~/UserControl/Note.ascx");
phUserContent.Controls.Add(ctr);
This Note.ascx contains some interesting controls and finally a LinkButton that fires an event. The LinkButton-code are very easy and gramatically correct,
<asp:LinkButton runat="server" ID="lbUpdate" OnClick="lbUpdate_Click" Text="Update"></asp:LinkButton>
In the Code behind for the ascx I have the code for the event,
protected void lbUpdate_Click(object sender, EventArgs e)
{ ... }
As I wroted, the postback occurs, the page are regenerated as I would suspect - but without the lbUpdate_Click event to be executed. A break-point is of course tried.
I'm looking for two possible scenarios. One is that I missed something really easy (you know, like wroted in wrong code behind file) or that I missed an important part of the Page Generation Cycle.
I'm mostly into the second, like this (i just think here..)
1. Page (ascx) got it's changes
2. Submit was clicked
3. Ascx was re-generated
4. Events was cleared but was exist and doesnt cast error.
5. After reload, initial content was reloaded
The effect would be that the compiler can't see the breakpoint and the values was never saved due to a "execution of an empty event". But this is just a amateours guess, please advice me.
[UPDATE AS PER ANSWER]
This is how I was solved it, based on the acepted answer below.
List<Control> ctr;
public User()
{
ctr = new List<Control>();
}
protected void Page_PreInit(object sender, EventArgs e)
{
ctr.Add(LoadControl("~/UserControl/Note.ascx"));
}
protected void Page_Load(object sender, EventArgs e)
{
ctr.ForEach(d => phUserContent.Controls.Add(d));
}
Shortly..
1. The class got a list of Controls
2. In Page_PreInit (before creation) add UC (u can have X of them here)
3. In Page_Load (where all ctr are created) add each UC to the PH.
Which also make the events in the UC also working, no magic and no dumb complications :-)
It's a lifecycle issue.
Remember, every page request creates a new Page object, and new instances of all the controls on it. If you are dynamically creating a control, then it has to be done in the exact same manner on every postback. If you want the new control to fire an event, then it has to have the same id as the old one, and have the event hooked up to it before control events are processed in the lifecycle.
If you're creating the control dynamically at a point in the page lifecycle that occurs after ViewState is handled, then you'll have to manage your own state as well. In other words, if you're not dynamically creating the control during the PreInit phase, then you'll have to manually deal with restoring state.

Getting data from child controls loaded programmatically

I've created 2 controls to manipulate a data object: 1 for viewing and another for editing.
On one page I load the "view" UserControl and pass data to it this way:
ViewControl control = (ViewControl)LoadControl("ViewControl.ascx");
control.dataToView = dataObject;
this.container.Controls.Add(control);
That's all fine and inside the control I can grab that data and display it.
Now I'm trying to follow a similar approach for editing. I have a different User Control for this (with some textboxes for editing) to which I pass the original data the same way I did for the view:
EditControl control = (EditControl)LoadControl("EditControl.ascx");
control.dataToEdit = dataObject;
this.container.Controls.Add(control);
Which also works fine.
The problem now is getting to this data. When the user clicks a button I need to fetch the data that was edited and do stuff with it.
What's happening is that because the controls are being added programmatically, the data that the user changed doesn't seem to be accessible anywhere.
Is there a solution for this? Or is this way of trying to keep things separated and possibly re-usable not possible?
Thanks in advance.
Just keep a reference to the control as a variable in the page's code-behind. I.e.
private EditControl control;
protected void Page_Init(object sender, EventArgs e)
{
control = (EditControl)LoadControl("EditControl.ascx");
control.dataToEdit = dataObject;
this.container.Controls.Add(control);
}
protected void Button_Click(object sender, EventArgs e)
{
var dataToEdit = control.dataToEdit;
}
As long as you're creating the control in the right part of the page's lifecycle (Initialization) then ViewState will be maintained. I'm assuming dataToEdit is just a TextBox or something?
Controls created dynamically must be added on Init or PreInit event on the page.
You have to do it here because controls state is not yet loaded. If you add the the control AFTER you'll have them empty since the page already filled control page values early in the page life cycle.
More info about page life cycle here
Here's my solution:
In the page, I keep a reference to the control that is loaded programmatically.
In the control I created a GetData() method that returns an object with the data entered by the user.
When the user submits the form, the page calls the GetData() method on the control to access the data the user entered.

Page Post back initializes the dropdownlist

I face a weird problem. I have a simple aspx page with a dropdownlist. The dropdown gets filled through a function which is called from Page_Load() event. The dropdown item selection triggers event OnSelectedIndexChanged. Now the event triggers rightly
but what happens that upon post back the dropdownlist gets initialized, that is, it shows empty. Never faced this type of issue before so i wonder what's happening wrong.
The piece of code follow:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
PopulateCompanyList(GetCompanies(serverUNCPath));
return;
}
Is ViewState disabled on your dropdownlist, or perhaps the whole application?
The very first ideas:
Check EnableViewState property of
your dropdown and all the parent
controls up to the root (should not be false)
You perform rebinding on postbacks without storing
SelectedValue property
If one of your parent controls is
custom or dynamic it may incorrectly
persist ViewState info (including children).

ASP.NET AJAX issues when using UserControls

I Have a UserControl called TenantList.ascx which contains a slightly modified GridView from DevExpress (Web.ASPxGridView). This control makes Callbacks without causing a postback which is exactly what I need.
The specific event I need to react on is CustomButtonClicked. I have made my on OnCustomButtonClicked event on the usercontrol TenantList.ascx that fires when the the GridView CustomButtonClicked event fires.
I have an eventhandler on the page where I use the UC. When I debug using VS I can see that I get into the eventhandler as I am suppose to.
My Eventhandler looks like this:
protected void uc_TenantList_CustomButtonCallback(object sender, ASPxGridViewCustomButtonCallbackEventArgs e)
{
Tenant tenant = (Tenant)uc_TenantList.GetGridView().GetRow(e.VisibleIndex);
switch (e.ButtonID)
{
case "btn_show":
ShowRow(tenant);
break;
case "btn_edit":
EditRow(tenant);
break;
case "btn_delete":
DeleteRow(tenant.Id);
break;
default:
break;
}
}
private void EditRow(Tenant tenant)
{
uc_TenantDetails.SetTenantData(cBLL.GetTenant(tenant.Id));
UpdatePanel1.Update();
}
The EditRow function get's called and the UserControl TenantDetails.ascx gets filled with data correctly. However the UpdatePanel1.Update(); is not updating the panel where my TenantDetails UserControl is in.
However if i call UpdatePanel1.Update(); from a normal control registered to the ScriptManager it updates just fine.
protected void Button1_Click(object sender, EventArgs e)
{
uc_TenantDetails.SetTenantData(cBLL.GetTenant(17));
UpdatePanel1.Update();
}
That works without a problem... I am 100% stuck and without any idea of what might be the problem here.
Any suggestion is welcome!!
Cheers
The Real Napster - In real trouble :)
Okay solved this issue
What I needed to do was to enable postback on the gridview control inside my usercontrol.
Then place the Gridview usercontrol in a updatepanel and still keep the details usercontrol in another updatepanel.
That way it all worked out. Not impressed by the solution though. Looks a bit ugly.
Make sure that your update panel is set to always update (not conditionally). You may also find the information in this articles useful:
http://www.asp.net/AJAX/Documentation/Live/overview/PartialPageRenderingOverview.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.updatepanel.update.aspx
The first link will give you some history regarding Partial Page Rendering, the second gives you some more information about the Update method.
From the documentation calling UpdatePanel.Update will cause an update panel to be re-rendered on the client after calling, but only if the UpdatePanel is set to Conditionally update. If it is set to always update this should throw an error.
If your update panel is set to always update, could it be that it is nested in another UpdatePanel which has its update mode set to conditional?

Resources