繁体   English   中英

使用ASP.net C#从html选择列表中获取所有项目

[英]Get all items from html select list using ASP.net C#

我有以下选择列表:

<select name="Context" id="Context" size="5">
<option>Context1</option>
<option>Context2</option>
<option>Context3</option>
<option>Context4</option>
<option>Context5</option>
</select>

我正在使用javascript上下移动此选择列表的项(正在运行)。 我想使用C#将生成的订单反馈回ASP.net。

如果我使用下面的代码行,则仅获得所选项目,如何获得整个列表?

 string items = Request.Form["Context"];

您可以得到所有类似的物品。

var ddlArray= new Array();
var ddl = document.getElementById('Context');
for (i = 0; i < ddl.options.length; i++) {
    ddlArray[i] = ddl .options[i].value;
}

现在,将此JavaScript数组传递给后面的代码。

一个答案是修改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>

请注意,我将其重命名为lstContext因为将其称为Context会导致构建失败(由于与现有Context对象共享名称)。

然后在您的代码中,以它们出现的顺序访问值:

for (int i = 0; i < lstContext.Items.Count; i++)
{
    string item = lstContext.Items[i].Value;
    // Do something with it
}

您的javascript仍应像对select一样在ListBox上工作,因此应保持不受影响。

创建一个隐藏字段(runat = server)并将改组后的<options>存储到该隐藏字段中; 您可以通过string itemsOrderedChanged = Request.Form[<HiddenFieldId>];在服务器端访问隐藏字段的内容string itemsOrderedChanged = Request.Form[<HiddenFieldId>];

尝试像这样将JavaScript值传递给隐藏字段。

var hidden=document.getElementById('hidValue');
var string strValues="";
for(var i=0i<ddlArray.Length;i++){
 strValues+=ddlArray[i]+",";
}

hidden.value=strValues;

并在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM