You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET中通过Ajax实现下拉列表联动:选择客户自动显示对应联系电话

解决ASP.NET中通过Ajax实现客户姓名与联系电话联动的问题

以下针对你提供的代码问题进行修正,实现选择客户姓名后自动匹配对应联系电话的功能:

原代码核心问题

  • WebMethod错误获取字段:返回Ledger_ID而非目标ContactNo字段
  • 存在SQL注入风险:直接拼接参数到SQL语句中
  • 前端跳转逻辑错误:误用服务器端Response.Redirect方法
  • 未处理数据为空场景:DataTable无数据时会引发索引越界异常

修正后的完整实现

1. 后端WebMethod修正

[WebMethod(EnableSession = true)] // 启用Session访问权限
public static QuotationModel GetCustomerDetail(int ledgerId)
{
    Services service = new Services();
    QuotationModel quotationModel = new QuotationModel();

    // 检查Session有效性
    if (HttpContext.Current.Session["BranchId"] == null)
    {
        quotationModel.Redirect = "YES";
        return quotationModel;
    }

    // 使用参数化查询杜绝SQL注入,仅查询需要的字段提升性能
    string qryGetCustomerDetail = @"
        SELECT ContactNo 
        FROM tbl_Ledger 
        WHERE Ledger_ID = @LedgerId 
          AND BranchId = @BranchId 
          AND Grup = 'CUSTOMER'";

    // 构建SQL参数
    SqlParameter[] parameters = new SqlParameter[]
    {
        new SqlParameter("@LedgerId", ledgerId),
        new SqlParameter("@BranchId", HttpContext.Current.Session["BranchId"])
    };

    DataTable dtGetCustomerDetail = service.GetDataTable(qryGetCustomerDetail, parameters); // 需确保Services类支持带参数的GetDataTable方法

    // 处理数据为空的情况
    if (dtGetCustomerDetail != null && dtGetCustomerDetail.Rows.Count > 0)
    {
        quotationModel.ContactNo = dtGetCustomerDetail.Rows[0]["ContactNo"].ToString();
        quotationModel.Redirect = "NO";
    }
    else
    {
        quotationModel.ContactNo = string.Empty;
        quotationModel.Redirect = "NO";
    }

    return quotationModel;
}

2. 前端Ajax代码修正

$("#cmb_customer").change(function () {            
    var ledgerId = $(this).val(); // 简化选中值获取逻辑
    var dataToSend = JSON.stringify({ ledgerId: ledgerId });

    $.ajax({
        type: "POST",
        url: "Quotation.aspx/GetCustomerDetail",
        async: true,
        data: dataToSend,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.d.Redirect === "YES") {
                window.location.href = "Index.aspx"; // 前端正确跳转方法
            }
            else {
                // 给联系电话下拉框设置选中值(需确保下拉框选项中存在该ContactNo)
                $("#cmb_contactno").val(data.d.ContactNo);
                // 若无需下拉选择,建议改用只读文本框:$("#txt_contactno").val(data.d.ContactNo);
            }
        },
        error: function (xhr, status, error) {
            // 增加错误详情便于调试
            $('#result').html(`<p>请求错误:${error}</p>`);
        },
        complete: function () {
            $('#loadingOverlay').hide();
        }
    });
});

3. 下拉框绑定优化(可选)

如果仅需显示对应客户的联系电话,无需下拉选择,建议将联系电话控件改为只读文本框,更符合业务逻辑:

<asp:DropDownList ID="cmb_customer" runat="server" ClientIDMode="Static"></asp:DropDownList>
<asp:TextBox ID="txt_contactno" runat="server" ClientIDMode="Static" ReadOnly="True"></asp:TextBox>

若坚持使用DropDownList,需确保绑定代码中cmb_contactno的Value与Text均为ContactNo,避免匹配失败:

// 修正绑定代码,添加参数化查询避免SQL注入
string contactWhere = "BranchId = @BranchId and Grup = 'CUSTOMER' and ContactNo != ''";
SqlParameter[] contactParams = new SqlParameter[] { new SqlParameter("@BranchId", Session["BranchId"]) };
service.BindDropdownList(cmb_contactno, "tbl_Ledger", "ContactNo", "ContactNo", contactWhere, contactParams, "SELECT CONTACT NO.");

内容的提问来源于stack exchange,提问作者s.k.Soni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 13:17:05