Reputation: 4730
I'm working on ASP.NET 4.0 and I'm having problems for saving the selected value in a DropDownList.
I initialize it in the Web Control's PreRender method as follows:
if (!Page.IsPostBack)
LoadCountryList();
Where LoadCountryList's code is:
private void LoadCountryList()
{
var vr = new CountryRepository();
var countryList = vr.GetAllForList();
DdlCountry.EnableViewState = true;
DdlCountry.DataValueField = "code";
DdlCountry.DataTextField = "name";
DdlCountry.DataSource = countryList;
DdlCountry.DataBind();
}
After I submit the form, I've noticed the DropDownList is empty(it's not before postback). If you take a look at my code, I've enabled the ViewState for this control, but I'm not getting any results yet. Does anybody know what's going on?
EDIT:
Here is the simple code of the control in the aspx file:
<asp:DropDownList Runat="server" ID="DdlCountry">
</asp:DropDownList>
Upvotes: 3
Views: 18059
Reputation: 7251
If it's in prerender, then that's before ViewState is initialized, so you're not reloading the data on a postback and you're also not able to get from ViewState because it's not put in there. The best thing with dropdowns is to load 'em up even on postback, but with some caching involved. That way your ViewState isn't bloated, it still handles your event on postback, and you're not hammering your database.
UPDATE:
Correction. @StriplingWarrior is correct in the comment below about PreRender (it will load into ViewState when in PreRender). However, I don't see how you can get simpler than my suggestion. For dropdowns, do the following:
However, you can improve this by making sure your data is cached (as it will now be hit every time your page/control init is run), but unless it's high traffic, this isn't overly concerning..or at least, it needs to be evaluated along with all other caching/database concerns.
The biggest reason this is a way better solution in general (aside from fixing your issue), is that your ViewState doesn't get bloated unnecessarily with all your items (Base64-encoded to boot) while still being able to track the selected item in the dropdown (turning off ViewState for dropdowns makes it so you can't track your selected item without having to resort to viewing the form post value directly).
Upvotes: 10
Reputation: 156459
The ViewState and ASP.NET Page Lifecycle are strange beasts. You sometimes have to get just the right "timing." Try:
Good luck.
Upvotes: 0
Reputation: 37205
I observed this phenomenon if EnableViewState of the MasterPage is set to false. (VS2008)
My solution was to fill the dropdown both in GET and in POST, and to retrieve the SelectedValue from the Form variables in Page_Load:
if (IsPostBack)
{
dropdown.SelectedValue = Request.Form[dropdown.UniqueID];
}
Upvotes: 7