c# - 如何使用 ajax 使用数据库 ASP .NET C# 从另一个下拉列表中填充下拉列表
问题描述
我尝试使用数据库填充类别下拉列表中的类型下拉列表。但成功函数返回整个 HTML 页面作为结果,而不仅仅是下拉列表选项。
我的 js 脚本的这一行出现错误:
var jsondata=JSON.parse(result.d);
下面是我的代码背后的代码、HTML 和 JS。请帮忙。PS:我没有使用 MVC
[WebMethod]
public static string GetType(string category)
{
List<DocumentTypeModel> options = DocumentType.GetType(category);
var types = options.Select(item => new { item.CODE, item.TYPE }).ToList();
return JsonConvert.SerializeObject(types);
}
public class DocumentType
{
public static List<DocumentTypeModel> GetType(string category)
{
DataTable dt = MsSqlHelper.GetDataTable(string.Format("SELECT '-- Select Type --' AS [TYPE], '' AS CODE, 0 AS ID UNION SELECT [TYPE], CODE, ID FROM DOCUMENTTYPE WHERE CATEGORY = '{0}' ORDER BY ID", category), 2);
return dt.AsEnumerable()
.Select(x => new DocumentTypeModel()
{
TYPE = x.Field<string>("TYPE"),
CODE = x.Field<string>("CODE")
}).ToList();
}
}
public class DocumentTypeModel
{
public int ID { get; set; }
public string CATEGORY { get; set; }
public string TYPE { get; set; }
public string CODE { get; set; }
}
$(document).ready(function () {
$('#<% =cboCategory.ClientID %>').change(function () {
var selected = $('#<% =cboCategory.ClientID %>').val();
$.ajax({
url:"request.aspx/GetType",
type:"POST",
data:'{"category":'+selected+'}',
success: function (result) {
var jsondata=JSON.parse(result.d);
var varOptions="";
for(var i=0;i<jsondata.length;i++){
varOptions+='<option value="'+jsondata[i].Value+'">'+jsondata[i].Text+'</option>';
}
$('#<%= cboType.ClientID %>').html(varOptions);
}
});
});
});
<asp:DropDownList ID="cboCategory" runat="server">
<asp:ListItem Text="-- Select Category --" Value="0" />
<asp:ListItem Text="QMS Document" Value="QMS Document" />
<asp:ListItem Text="Internal - Technical Document" Value="Internal - Technical Document" />
<asp:ListItem Text="External - Technical Document" Value="External - Technical Document" />
</asp:DropDownList>
<asp:DropDownList ID="cboType" runat="server"></asp:DropDownList>
<script src="../Scripts/jquery-3.3.1.min.js"></script>
解决方案
success: function (data) {
var jsondata = JSON.parse(data.d);
$('#<%=ddlRegion.ClientID%>').empty();
$('#<%=ddlRegion.ClientID%>').append($("<option></option>").val("0").html("Choose Now"));
$.each(jsondata, function (key, value) {
$('#<%=ddlRegion.ClientID%>').append($("<option></option>").val(value.RegionID).html(value.Region));
});
},
你必须像这样在下拉列表中附加项目......在ajax的成功方法中
推荐阅读
- ffmpeg - VLC 可以读取 mp3 但 FFMPEG“找不到编解码器参数”
- web-services - SOAP 服务的 WSDL(带有基本身份验证)是否也需要身份验证?
- .net-core - 在 Azure devops 中从 Ubuntu 16.04 更新到 18.04 时在 % 前面插入空格
- selenium - 如何为范围报告中的每个步骤附加屏幕截图?
- javascript - HTML、CSS、JavaScript。画布将其他 div 推开
- css - 在laravel 8中缩小侧边栏时内容不会扩展
- python - python:将列表的每个元素组合成一个元组列表
- r - 根据列中的条件使用 dplyr 进行切片
- npm - 尽管我执行 npm login 后跟 npm install 命令,但 Npm install 不会安装安全包
- java - 如何使用新 Map 更新 Java HashMap