首页 > 解决方案 > 如何使用 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>

标签: c#ajaxdrop-down-menu

解决方案


   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的成功方法中


推荐阅读