首页 > 解决方案 > 在 asp.net 中使用 ajax 调用更新下拉列表

问题描述

我有带有用户电子邮件地址的下拉列表“ListBox”的网页。

当我在下拉列表中添加新的电子邮件用户时,如何创建一个更新下拉列表“ListBox”的功能?

我尝试了这个解决方案但没有成功,因为它清空了下拉列表,而不是添加新用户。

这是我的代码:

    nnewuser.txuser = $("[id*=txuser]").val();

    $.ajax({
        type: "POST",
        url: "prefix.aspx/Savepnusers" + qString,
        data: '{nnewuser: ' + JSON.stringify(nnewuser) + '}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        success: function (response) {
            if ($("[id*=txuser]").val()) {
                alert("Ok");
                alert(JSON.stringify(nnewuser));
                $("[id*=ListBox1]").html(response);                            
            }
        },

        failure: function (response) {
            alert(response.d);
        },

        error: function (response) {
            alert(response.d);
        },

        error: function (xhr, ajaxOptions, thrownError) {
            alert("error : " + thrownError + JSON.stringify(nnewuser));
        }
    });
    return false;
});

保存用户

public class pnnusers
{
    public string txuser { get; set; }
}

[WebMethod(EnableSession = true)]
[ScriptMethod]
public static void Savepnusers(pnnusers nnewuser)
{
    string sql = @String.Format(" INSERT INTO `tbl_email` (email) VALUES (?); ");

    using (OdbcConnection cn =
      new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
    {
        using (OdbcCommand command =
                new OdbcCommand(sql, cn))
        {
            try
            {
                command.Connection.Open();
                command.Parameters.AddWithValue("param1", nnewuser.txuser.ToString());
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                command.Connection.Close();
            }
        }
    }
}

下拉列表

private void MTListBox1()
{
    DataTable dt = new DataTable();

    sql = @String.Format(" SELECT ");
    sql += String.Format(" LOWER(Email) AS UserEmail ");
    sql += String.Format(" FROM ");
    sql += String.Format("  tbl_email ORDER BY LOWER(Email) ASC; ");

    using (OdbcConnection cn =
        new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
    {
        using (OdbcCommand command =
            new OdbcCommand(sql, cn))
        {
            try
            {
                command.Connection.Open();
                OdbcDataAdapter sqlDa = new OdbcDataAdapter(command);
                sqlDa.Fill(dt);

                if (dt.Rows.Count > 0)
                {
                    ListBox1.DataTextField = "UserEmail";
                    ListBox1.DataValueField = "UserEmail";
                    ListBox1.DataSource = dt;
                    ListBox1.DataBind();
                }
            }
            catch (OdbcException ex)
            {
                string msg = "Fetch Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }
            finally
            {
                command.Connection.Close();
            }
        }
    }
}

标签: c#asp.netjsonajax

解决方案


这里有两个主要问题:

首先,您的Savepnusers方法不返回任何内容,因此您不能在 AJAX 调用中使用响应。您需要的是在成功完成ListBox1后重新初始化或附加新项目Savepnusers

其次,您似乎无法nnewuser正确发送参数。您不需要pnnusers类,只需使用string类型作为参数。

所以服务器端:

public static void Savepnusers(string nnewuser)

在客户端,您需要使用 jquery 添加下拉列表项:

var txtUser = $("[id*=txuser]").val();
$.ajax({
        type: "POST",
        url: "prefix.aspx/Savepnusers",
        data: JSON.stringify({ nnewuser: txtUser }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        success: function () {
            //Since you can't use response object, you can append new item  to dropdownlist
            if (txtUser) {
               $("[id*=ListBox1]").append('<option value="'+txtUser+'">'+txtUser+'</option>');         
            }

        },

        failure: function (response) {
            alert(response.d);
        },

        error: function (response) {
            alert(response.d);
        },

        error: function (xhr, ajaxOptions, thrownError) {
            alert("error : " + thrownError + JSON.stringify(nnewuser));
        }
    });

请参阅:来自 javascript 问题的 asp 下拉列表动态值


推荐阅读