簡體   English   中英

使用Jquery的ASP.NET Ajax調用添加到列表

[英]ASP.NET ajax call using Jquery adds to list

我有一個簡單的UI,在其中嘗試使用數據庫中的數據填充選擇下拉列表。 我正在通過AJAX調用來獲取數據。

C#Web方法看起來像

private static List<List<string>> componentTypeDropDown = new List<List<String>>();

private void loadDropDownList()
{
    OleDbConnection conn = new OleDbConnection(connectionString);
    OleDbCommand cmd = new OleDbCommand("SELECT FieldName,FieldLabel FROM dropDownFields", conn);
    conn.Open();
    OleDbDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
       List<String> temp = new List<string>();
       temp.Add((string)dr.GetValue(0));
       temp.Add((string)dr.GetValue(1));
       componentTypeDropDown.Add(temp);
       conn.Close();
    }
}

[WebMethod]
public static ArrayList getComponentType()
{
    ArrayList compType = new ArrayList();
    for (int i=0;i<componentTypeDropDown.Count();i++)
    {
       compType.Add(new { label = componentTypeDropDown[i][0], value = componentTypeDropDown[i][1] });
    }
    return compType;
}

AJAX呼叫看起來像

$.ajax({
    type: "POST",
    url: "salesQuote.aspx/getComponentType",
    data: "",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
          console.log("karan");
    },
    error: function () {                   
          alert("Failed to load names");
    }
});

每次刷新或什至重新啟動服務器時,成功回調中的msg值也會具有以前的值。 例如,假設我的數據庫的值為1,2。 第一次調用ajax msg是1,2,如果我刷新,則值為1,2,1,2,依此類推。 即使我關閉服務器並重新啟動,該值也將是1,2,1,2,1,2

您的ComponentTypeDropdown是靜態的,因此,每次調用“ LoadDropdownList”時,此列表都會添加新項目,而不會刪除舊項目。

我建議您在loadDropDownList方法中添加以下行:

 private void loadDropDownList()
    {
        componentTypeDropdown.RemoveAll();
        OleDbConnection conn = new OleDbConnection(connectionString);
        OleDbCommand cmd = new OleDbCommand("SELECT FieldName,FieldLabel FROM dropDownFields", conn);
        conn.Open();
        OleDbDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
           List<String> temp = new List<string>();
           temp.Add((string)dr.GetValue(0));
           temp.Add((string)dr.GetValue(1));
           componentTypeDropDown.Add(temp);
           conn.Close();
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM