[英]Get all items from html select list using ASP.net C#
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). 我正在使用javascript上下移动此选择列表的项(正在运行)。 I would like to feed the resulting order back to ASP.net using C#.
我想使用C#将生成的订单反馈回ASP.net。
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. 现在,将此JavaScript数组传递给后面的代码。
One answer is to modify the select
to make it a ListBox
and then access it programattically on the server: 一个答案是修改
select
以使其成为一个ListBox
,然后在服务器上以编程方式对其进行访问:
<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). 请注意,我将其重命名为
lstContext
因为将其称为Context
会导致构建失败(由于与现有Context
对象共享名称)。
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. 您的
javascript
仍应像对select
一样在ListBox
上工作,因此应保持不受影响。
create a hidden field (runat=server) and store the shuffled <options> into the hidden field; 创建一个隐藏字段(runat = server)并将改组后的<options>存储到该隐藏字段中; You can access content of hidden field at server side by
string itemsOrderedChanged = Request.Form[<HiddenFieldId>];
您可以通过
string itemsOrderedChanged = Request.Form[<HiddenFieldId>];
在服务器端访问隐藏字段的内容string itemsOrderedChanged = Request.Form[<HiddenFieldId>];
try to pass JavaScript value to hidden field like this . 尝试像这样将JavaScript值传递给隐藏字段。
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. 并在page_load或what_ever事件中获取此字符串并将其拆分。
protected HtmlControls.HtmlInputHidden hidValue;
protected void Page_Load(object sender, System.EventArgs e)
{
dynamic hiddenValue = hidValue.Value;
string [] arr=hiddenValue.Split(",");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.