Atif Imtiaz
Atif Imtiaz

Reputation: 225

Get selected value of Javascript Modified Dropdownlist in C#

I have a dropDownlist in my project and i am adding items to it in javascript. Now i want to get selected index in C# (on a button click event). But i am unable to do this because it seems to be a problem that viewstate is not maintained. Further more i have

EnableEventValidation="false" 

in my Page Please tell me how can i achieve this functionality? Right Now i am adding selected values in a hidden field and then accessing that hidden field in C#. Its working but i want "cleanliness".

Regards

Upvotes: 1

Views: 1458

Answers (1)

Denys Wessels
Denys Wessels

Reputation: 17049

When ASP.NET performs a form POST the drop down options need to be passed through to the server and be recreated there for further processing.This is achieved through ViewState.

I'm not aware of any other way of doing this, what you can do however is retrieve the selected value of the drop down using Request.Form[ddlProducts.UniqueID] if you can figure out the item index based on the selected value, great! Else I think hidden fields are your only option

Here's a complete example:

<head runat="server">
    <title></title>
    <script type="text/javascript">
        window.onload = function () {
            var select = document.getElementById("ddlProducts");
            select.options[select.options.length] = new Option('Product 1', 'Value 1');
            select.options[select.options.length] = new Option('Product 2', 'Value 2');
            select.options[select.options.length] = new Option('Product 3', 'Value 3');
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="ddlProducts" runat="server">
        </asp:DropDownList>
        <asp:Button ID="btnOK" runat="server" Text="OK" OnClick="Process" />&nbsp;<span id="output"
            runat="server" />
    </div>
    </form>
</body>
</html>

protected void Process(object sender, EventArgs e)
{
    int selectedIndex = ddlProducts.SelectedIndex;
    output.InnerHtml = Request.Form[ddlProducts.UniqueID];
}

Upvotes: 1

Related Questions