简体   繁体   English

如何从Web服务列表中填充dropDownList <string>

[英]How to populate a dropDownList from a webservice list<string>

I am able to populate my DropDownList and select a value from the list. 我能够填充我的DropDownList并从列表中选择一个值。 However, I am never able to get the value that I selected. 但是,我永远无法获得我选择的价值。 Let me show you what I am doing. 让我告诉你我在做什么。 I have the following DropDownList 我有以下DropDownList

<asp:DropDownList ID="mobility" runat="server" AppendDataBoundItems="true">

I populate the above DropDownList using the following AJax. 我使用以下AJax填充上面的DropDownList。

    function load_mobilityList() {
    $.ajax({
        url: '<%=ResolveUrl("/api/facility/getFacilityMobility_LOV") %>',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        type: "GET",
        success: function (Result) {
            //Result = Result.d;
            $.each(Result, function (key, value) {
                $("#mobility").append($("<option></option>").val
                (key).html(value));
            });
        },
        error: function (Result) {
            alert("Error");
        },
        failure: function (Result) {
            alert(response.responseText);
        }
    });
}

The URL that is used in the AJAX above to populate the DropDownList is calling a web service. 上面用于填充DropDownList的AJAX中使用的URL是调用Web服务。 This is the module. 这是模块。 The Module returns a "List" and I really would like to keep it that way if possible. 该模块返回一个“列表”,我真的希望尽可能保持这种方式。

        public List<String> getFacilityMobility_LOV()
    {

        string constr = ConnectionStringsExpressionBuilder.GetConnectionString("ConnectionString");
        OracleConnection con = new OracleConnection(constr);
        con.Open();

        string sqlStrg = "SELECT mobility_type FROM lu_mobility_type order by upper(mobility_type)";
        // create command object and set attributes
        OracleCommand cmd = new OracleCommand(sqlStrg, con);

        List<string> myList = new List<string>();
        using (OracleDataReader rd = cmd.ExecuteReader())
        {
            var idx1 = rd.GetOrdinal("mobility_type");
            while (rd.Read())
            {
                myList.Add(rd.GetString(0));
            }
        }

        con.Close();

        return myList;
    }

OK, now the DropDownList is populated as expected. 好的,现在按预期填充DropDownList。 Everything looks good so far. 到目前为止一切看起来都很好。

Image of DropDownList with populated values. DropDownList的图像,带有填充值。

So, here is the problem. 所以,这是问题所在。 When I select an item in the DropDownList and submit the form, I am unable to get the value that I selected. 当我在DropDownList中选择一个项目并提交表单时,我无法获得我选择的值。 Here is a snippet of the C# CodeBehind: 这是C#CodeBehind的片段:

        string hey = mobility.SelectedItem.Value;
        string hey2 = mobility.SelectedItem.Text;
        string hey1 = mobility.SelectedValue;

Using the MS Visusal Studio I can see the values of the above variables: 使用MS Visusal Studio我可以看到上述变量的值:

  • hey : "Select Mobility Type" 嘿:“选择移动类型”
  • hey2 : "Select Mobility Type" 嘿2:“选择移动类型”
  • hey1 : "Select Mobility Type" 嘿1:“选择移动类型”

No matter what value I select in the DropDownList, I always get the save values that I show above. 无论我在DropDownList中选择什么值,我总是得到上面显示的保存值。 Why? 为什么? What am I missing? 我错过了什么?

You need to attach a JavaScript function to your drop down that set's the value of a hidden text field (on selected index changed) to the value of your mobility drop down list. 您需要将JavaScript函数附加到下拉列表中,该函数将隐藏文本字段的值(在所选索引已更改时)设置为移动性下拉列表的值。 Then read the value of that hidden text box in your C# code behind. 然后在后面的C#代码中读取该隐藏文本框的值。

Edit 编辑

This is a quick and dirty fully working example 这是一个快速而肮脏的完整工作示例

<asp:DropDownList ID="mobility" runat="server" ClientIDMode="Static">
    <asp:ListItem>-- Select a Mobility Type --</asp:ListItem>
</asp:DropDownList>

<asp:Button runat="server" ID="btnGo" text="Go" OnClick="btnGo_Click"/>
<input type="hidden" id="txtHidden" runat="server" ClientIDMode="Static"/>

<br /><br />
Value of Drop Down Is: <asp:Label runat="server" ID="lblOutput" />

<script>
    $(document).ready(function () {

        // set the value
        $("#mobility").append($("<option></option>").val("my Value").html("my Value"));

        //on change event
        $("#mobility").change(function () {
            $("#txtHidden").val($("#mobility").val());
        })

    });        
</script>

Then the code behind 然后是代码背后

    protected void btnGo_Click(object sender, EventArgs e)
    {
        lblOutput.Text = txtHidden.Value;
    }

@Joe Raio is right, The values you have added from javascript are not present in ViewState object, so you really need to save the selected value to another controller that can be read from both sides. @Joe Raio是对的,您从javascript添加的值在ViewState对象中不存在,因此您确实需要将所选值保存到另一个可以从两侧读取的控制器。

OnChange you set the value of a hidden field to the selected value from dropdown list, then you can read it from code behind. 在OnChange中,您可以从下拉列表中将隐藏字段的值设置为所选值,然后您可以从后面的代码中读取它。

Edit 编辑

What I mean is this: 我的意思是:

you add a hidden field in you markup: 在标记中添加隐藏字段:

<asp:Hidden runat="server" ID="dropSelectedValue" ClientIdMode="Static" />

then into your javascript success function, you init the first value 然后进入你的javascript成功函数,你初始化第一个值

// your code as is
$("#dropSelectedValue").val(firstValue);
// continues...

then you add an event for tracking changes: 然后添加一个事件来跟踪更改:

$(function(){
$("#mobility").onchange(function(){
$("#dropSelectedValue").val($('#mobility').val());
});
});

and finally you can read your selected value from c# by reading hidden field value. 最后,您可以通过读取隐藏字段值从c#中读取您选择的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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