I have the following select list:
<select name="Context" id="Context" size="5">
<option>Context1</option>
<option>Context2</option>
<option>Context3</option>
<option>Context4</option>
<option>Context5</option>
</select>
I am using javascript to move the items of this select list up and down (this is working). I would like to feed the resulting order back to ASP.net using C#.
If I use the following line of code I get only the selected item, how do I get the whole list?
string items = Request.Form["Context"];
You can get all items like this.
var ddlArray= new Array();
var ddl = document.getElementById('Context');
for (i = 0; i < ddl.options.length; i++) {
ddlArray[i] = ddl .options[i].value;
}
Now pass this JavaScript array to your code behind.
One answer is to modify the select
to make it a ListBox
and then access it programattically on the server:
<asp:ListBox runat="server" name="lstContext" id="lstContext" size="5">
<asp:ListItem>Context1</asp:ListItem>
<asp:ListItem>Context2</asp:ListItem>
<asp:ListItem>Context3</asp:ListItem>
<asp:ListItem>Context4</asp:ListItem>
<asp:ListItem>Context5</asp:ListItem>
</asp:ListBox>
Note that I renamed it lstContext
as calling it Context
will cause build failures (due to sharing a name with the existing Context
object).
Then in your code, to access the values in the order they appear:
for (int i = 0; i < lstContext.Items.Count; i++)
{
string item = lstContext.Items[i].Value;
// Do something with it
}
Your javascript
should still work on the ListBox
as it does for the select
, so this should remain unaffected.
create a hidden field (runat=server) and store the shuffled <options> into the hidden field; You can access content of hidden field at server side by string itemsOrderedChanged = Request.Form[<HiddenFieldId>];
try to pass JavaScript value to hidden field like this .
var hidden=document.getElementById('hidValue');
var string strValues="";
for(var i=0i<ddlArray.Length;i++){
strValues+=ddlArray[i]+",";
}
hidden.value=strValues;
And in page_load or what_ever event get this string and split it.
protected HtmlControls.HtmlInputHidden hidValue;
protected void Page_Load(object sender, System.EventArgs e)
{
dynamic hiddenValue = hidValue.Value;
string [] arr=hiddenValue.Split(",");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.