【问题标题】:How can i fill a DropDown list using ajax and a c# method如何使用 ajax 和 c# 方法填充下拉列表
【发布时间】:2019-11-21 19:44:38
【问题描述】:

嗨,我的 c# 方法是这样的:

[WebMethod] 
    protected static void fillList(HiddenField hiddenControl, System.Web.UI.WebControls.DropDownList listinc)
    {
        int dato = 0;
        string strSql;
        dato = Convert.ToInt32(hiddenControl.Value);

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString());
        conn.Open();
        strSql = "SELECT DISTINCT incid FROM HisReportes WHERE peri = " + dato;
        SqlCommand camAND = new SqlCommand(strSql, conn);
        System.Data.DataTable tablainc = new System.Data.DataTable();
        camAND.CommandTimeout = 36000;
        tablainc.Load(camAND.ExecuteReader());

        foreach (DataRow dtrw in tablainc.Rows)
        {            
           listinc.Items.Add(dtrw[0].ToString());
        }

    }

我用 onlick 函数进行了测试,它可以工作,但我需要从 Ajax 函数中调用它:

$.ajax({
        type: "POST",
        url: "Incio.aspx/fillList",
        data: '{hiddenControl , listinc, dtrw }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data)
            {
                $.each(data, function (){
                    $("listinc").append($("<option     />").val(this.incidente).text(this.dtrw[0]));
                });
            },
            failure: function () {
                alert("Failed!");
            }
        });

这是我的 ajax 函数,但它没有填充下拉列表。

【问题讨论】:

  • 怎么不工作了?您收到错误消息吗?
  • 它没有填满下拉列表。
  • 所以您没有收到错误消息? alert 会响吗?
  • 是的,警报正在处理消息“失败”
  • 这段代码发生了很多奇怪的事情。第一个 fillList 方法需要 2 个参数,但您的 ajax 只发送一个参数并且它甚至不匹配。其次,您的代码对 SQL 注入开放。我认为您需要知道客户端/服务器端如何通信。您可以查看How to fill a DropDown using Jquery Ajax Call?

标签: javascript c# asp.net ajax


【解决方案1】:

您需要从 WebMethod 返回列表,我建议您从 WebMethod 返回一个字符串数组。

    [WebMethod]
    public static string[] fillList()
    {
        your code here....
        return listinc.ToArray();
    }

那么,在成功函数中导入Ajax

    $.ajax({
      type: "POST",
      url: "./Inicio.aspx/fillList",
      ...
      success: function (data) {
          let data = data["d"];
          let dropdown = $("#listinc");

          for (let i = 0; i < data.length; i++) {
            // put here your data
            dropdown.append(`<option>${ data[i] }</option>`);
          }
       }
    });

【讨论】:

  • 你将不得不在你的 web 方法中传入那个隐藏字段值,以便他可以在 SQL 语句中使用
  • 当然,这只是一个例子。
猜你喜欢
  • 1970-01-01
  • 2013-07-19
  • 2017-08-26
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
  • 1970-01-01
  • 2012-11-08
相关资源
最近更新 更多