s.k.paul
s.k.paul

Reputation: 7301

Retrieve HtmlSelect option values from asp.net code behind

I have a HTML select control in ASP.Net WebForm application. Its option values are added from jquery in client side. I would like to read those values from server side when the page is posted back. I have the following code, but it does not work. Option values added from client side are not available in code behind. How can i make those values available to code behind?

//Client code
<select title="Select one" id="selectBooks" multiple="multiple">
     <option value="1">test</option> //added in client side.
</select>

//Code behind
System.Web.UI.HtmlControls.HtmlSelect books= (System.Web.UI.HtmlControls.HtmlSelect)form1.FindControl("selectBooks");

foreach (ListItem item in books.Items)
{
   string test = item.Text.ToString();
}

Upvotes: 0

Views: 1871

Answers (3)

Amit Sharma
Amit Sharma

Reputation: 11

ASP code:

Request["selectedBooks"]

Hopefully this will work.

Upvotes: 1

DK Chauhan
DK Chauhan

Reputation: 194

Here i suggest you to keep a hidden field on the page where you HTML select control is

then on clientclick event of some button set all selected values of HTML select in this hidden field. like HdnValues.value="1,2,3,4";

now on post back you can find the hidden field value on server.

Upvotes: 0

Kristof
Kristof

Reputation: 3315

Your server can only know of data that is being submited to it.
Adding an option to a select control will just add it client side.
The value will be submitted if the users selects it but otherwise your server will never receive that data.
If you must have the extra values you have to make sure that they reach the server one way or another.

The first idea that pops to my mind is adding the values to a hidden input field as well as the select control so that when the user does a postback you can read the values from the inputfield.
Something like this :

//Client code
<input id="selectionData" runat="server" type="hidden" value="2--addedvalue1;3--addedvalue2"/>
<select title="Select one" id="selectBooks" multiple="multiple">
     <option value="1">test</option>
     <option value="2">addedvalue1</option> //added in client side.
     <option value="3">addedvalue2</option> //added in client side.
</select>

//Server side
var data = selectionData.Value;
//add code to parse the data

Upvotes: 0

Related Questions