如何从asp.net代码中获取Select2值

时间:2022-11-27 19:32:21

I have Dropdownlist that has only one element:

我有Dropdownlist只有一个元素:

<asp:DropDownList CssClass="select2" ID="ddl" runat="server" />

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        ddl.Items.Add(new ListItem("text", "value"));
    }
}

Also my ddl gets data from ajax call. When I'm trying to get changed value from code behind it still returns value of first element.

我的ddl也从ajax调用中获取数据。当我试图从代码后面改变值时,它仍然返回第一个元素的值。

 string value = ddl.SelectedValue; //I got data from ajax call, changed value but it still returns first "value"

But from javascript I can get changed value, so now on every change in my ddl I copy value to hidden field so I can get value from codebehind

但是从javascript我可以得到更改的值,所以现在我的ddl中的每个更改都将值复制到隐藏字段,这样我就可以从代码隐藏中获取价值

$("#ddl").change(function () {
   $('#hidden_for_ddl').val($("#ddl").val());
});

Finally I can get selected value from code, is it easier way to solve my problem?

最后我可以从代码中获取选定的值,是否更容易解决我的问题?

string value = hidden_for_ddl.Value; //returns "selected value"

1 个解决方案

#1


0  

string value = Empty.String;
foreach (ListItem item in ddl) {
    if ((item.Selected == true)) {
value = item.Value;
return;
    }
}

This will go through each item and set the string value when it finds one that is selected.

这将遍历每个项目,并在找到所选项时设置字符串值。

#1


0  

string value = Empty.String;
foreach (ListItem item in ddl) {
    if ((item.Selected == true)) {
value = item.Value;
return;
    }
}

This will go through each item and set the string value when it finds one that is selected.

这将遍历每个项目,并在找到所选项时设置字符串值。