views:

385

answers:

1

I have an asp.net dropdownlist control. There are two ways it can be selected.

The first is through a button that sets the value in the drop-down list via javascript.

The second is by manually selecting the dropdownlist option.

Each of these methods work by themselves.

If I do the first followed by the second and then hit save - the value that is saved is the value set by the javascript. The manual selection did not have any effect.

Does anyone know why this is the case?

EDIT:

In the HTML Head section:

<script>
function Select(allocationId) {
    document.getElementById('Accounts').value=allocationId;
}
</script>

In the HTML Body:

<asp:DropDownList ID="Accounts" runat="server"></asp:DropDownList>
<button onclick="Select(<%#"'" + DataBinder.Eval(Container.DataItem, "Associated_AccountId")  + "'"%>)" type="button">Select</button>
<asp:Button ID="btn_SaveAndClose" runat="server" Text="Save and Close" OnClick="btn_SaveAndClose_Click"></asp:Button>

In the code behind:

protected void btn_SaveAndClose_Click(object sender, System.EventArgs e)
{
   int id = Convert.ToInt32(this.Accounts.SelectedValue);
}

EDIT:

Funnily enough - when I use:

int id =  Convert.ToInt32(Request.Form["Accounts"]);

it works. But I don't know why.

+1  A: 

The most common mistake that would cause this is that you're likely populating or binding that DropDownList every Page_Load or Init, thus erasing whatever state you entered the page with. Be sure to do a (!IsPostBack) check before populating your DropDownList.

This worked for me: (try removing the !IsPostBack check and see if the behavior is similar to what you're seeing in your app)

page content

<asp:DropDownList ID="ddlTest" runat="server"></asp:DropDownList>
<button onclick="select(3);">Select Three</button>
<asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" />
<script type="text/javascript" language="javascript">
    //<![CDATA[
    function select(value) {
        var ddlTest = document.getElementById('<%=ddlTest.ClientID%>');
        for (var i = 0; i < ddlTest.options.length;  i++) {
            if (ddlTest.options[i].value == value) {
                ddlTest.selectedIndex = i;
                return;
            }
        }
    }
//]]>
</script>
<asp:Label ID="lblResult" runat="server"></asp:Label>

Code Behind

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        PopulateDropDown();
}
protected void btnSave_Click(object sender, EventArgs e)
{
    lblResult.Text = ddlTest.SelectedValue;
}
void PopulateDropDown()
{
    Dictionary<int, string> data = new Dictionary<int, string>();
    data.Add(1, "One");
    data.Add(2, "Two");
    data.Add(3, "Three");
    ddlTest.DataSource = data;
    ddlTest.DataTextField = "Value";
    ddlTest.DataValueField = "Key";
    ddlTest.DataBind();
}
blesh
Alternatively you can populate in OnInit instead of OnLoad, which will still work even if you disable ViewState.
Richard Szalay