Search code examples
c#asp.netdropdownlistfor

Dynamic Dropdownlist value not showing using server tags


I'm currently using this code to try to populate my dropdown list in asp.

for (int i = 0; i < items.Count; i++)
{
    models.Add(i+1, items.ElementAt(i).model);
}
ddl_Model.DataTextField = "Value";
ddl_Model.DataValueField = "Key";
ddl_Model.DataSource = models;
ddl_Model.DataBind();             

However, upon using SelectedItem or SelectedValue, it always show as though my list is empty.

I believe it's due to me declaring an empty list from the start, before populating it.

<h2>Please Select your Model:</h2>
<asp:DropDownList ID="ddl_Model" AppendDataBoundItems="True"  runat="server" >
</asp:DropDownList>

May I know how to get the correct values from my drop down list?

Thanks in advance.


Solution

  • This is the ViewState issue. Basically your dropdown is not retaining state during PostBack event. First thing is check whether you have enabled the view state for the page.

    <asp:Page EnableViewState="True" />
    

    Second thing is check where you are populating the dropdown. If you are binding in the page load event, then make sure if it is under !IsPostBack or not

    if(!IsPostBack)
    {
    //your above code
    }
    

    Third thing is using debug, check whether ddl_Model.SelectedIndex is called after ddl_Model.DataBind() code is called.