首页 > 解决方案 > 如何使用 jQuery 设置 Asp.Net DropDownList 的值?

问题描述

我有一个 Asp.Net 表单:

<div id="my-fields">
   <asp:TextBox ID="Name" runat="server" />
   <asp:TextBox ID="Age" runat="server" />
   <asp:DropDownList ID="Dept" runat="server" required="true">
        <Items>
             <asp:ListItem Text="Human Resources" value="HR"/>
             <asp:ListItem Text="Information Technology" value="IT"/>
        </Items>
   </asp:DropDownList> 
</div>

在“名称”文本框中输入文本时,我正在对 Web API 进行 AJAX 调用,该 API 获取 Age 和 DropDownList 字段的值并使用这些值自动填充这些字段。

这是用于将值从 Web API 设置到字段的 jQuery:

 $("#my-fields input[id*='Name']").val(name);
 $("#my-fields input[id*='Age']").val(age);
 ***$("#my-fields select[id*='Dept']").val(dept);***

问题是我从 Web API 获得的“部门”的价值是,例如:“人力资源”。ListItem 的值为“HR”。如何自动填充下拉字段?

标签: javascripthtmljqueryasp.netwebforms

解决方案


您可以为此使用 jQuery append

<asp:DropDownList ID="Dept" runat="server" required="true" ClientIDMode="Static">
    <Items>
        <asp:ListItem Text="Human Resources" Value="HR" />
        <asp:ListItem Text="Information Technology" Value="IT" />
    </Items>
</asp:DropDownList>

<script>
    var $DeptDll = $('#Dept');

    //if you want to empty it first
    $DeptDll.empty();

    $DeptDll.append($('<option></option>').text('New Text Value').val('NTV'));
</script>

推荐阅读