javascript - 如何使用 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”。如何自动填充下拉字段?
解决方案
您可以为此使用 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>
推荐阅读
- asp.net-mvc - 如果在响应标头中同时传递 X-Frame-options SAMEORIGIN 和 DENY 会发生什么?
- excel - Excel VBA - 改进全局变量使用的技巧
- amazon-ec2 - 如何使用 ec2_sd_config 和 blackbox exporter 进行多目标和多端口服务状态检查。?
- python - ValueError:使用序列设置数组元素。ValueError:无法将 NumPy 数组转换为张量(不支持的对象类型系列)
- java - 我的代码实现 RSA 有什么问题?
- c# - NSubstitute 在基准测试中分配内存
- shapefile - 地理绘图英国(ONS)县形状文件(shp)的问题
- node.js - 从 Firestore 子集合中获取第一个文档和主文档?
- android - 64 位本机库的使用被禁用,但 App Bundle 仅包含 64 位本机库
- curl - 如何在 groovy URL 请求中设置表单数据?