OK so here is the scenario,  you have a data bound control, plain old vanilla DropDownList that is bound to a DataReader.  What you need to do is add values to the dropdown list from JavaScript and then retrieve the new value on the code behind after the user submits the form.

Part 1- jQuery Goodness

Adding the item to the DropDownList (now we are on the html side so we need to think in terms of html namely the <select> tag.)  I mean adding the item to the select list is easy.

ASPX markup

<label>My Drop Down List</label>
<asp:DropDownList runat="server" ID="ddlMyDropDown" CssClass="ddlMyDropDown" ></asp:DropDownList>
<br />
<br />
<input type="text" id="addToDropDown" class="addToDropDown" />

 

jQuery code that will add the value from the text box to the drop down and select the newly added value

// first lets un-select any items that have been selected
$("select.ddlMyDropDown option:selected").removeAttr("selected");
var addvalue=$("#addToDropDown").val(); 
$("select.ddlMyDropDown").prepend('<option selected="selected" value="' + addvalue + '">' + addvalue+ '</option>');

As a note you will notice that I am using the class to select the DropDownList(I mean the html select).  I am doing this because I am assuming that you are going to use a MasterPage which is an INamingContainer that will mess with your id's.  (This is one of the reasons that jQuery rocks if you know your CSS 3 selectors
you will be able to select virtually anything on the page with jQuery and manipulate it as needed)

ASP.NET Tweaks

Ok so now on the server side this is where it gets a bit tricky. You first need to un-enable Validation which is a "feature" of .Net 2.0+ namely whenever you use databinding with a DropDownList all the values are added to ViewState so that ASP.NET knows what values are valid in the drop down list.

<pages enableEventValidation="false">

 

The next gotcha is the same as before only different.  So by disabling Event Validation we are no longer going to get an error screen at the time of the post back but we still can't retrieve the value via the SelectedValue property of the control.  Instead we need to grab the value from the Form.

// this won't work ddlMyDropDown.SelectedValue
string selected = Request.Form[ddlMyDropDown.UniqueID];

You probably know this but just as a reminder.  The "UniqueID" of a control in the html world is the "name" property and the ClientID is the "id" property of the html, when retrieving values from the Form you need to use the name of the html element hence why we used the UniqueID..

Submit this story to DotNetKicksShout it   Bookmark and Share