2016-03-18 21 views
0

我想在頁面上寫一個自動完成功能,用戶可以在文本框中輸入字符,並且下拉菜單會爲它檢索到的地址提供選項字符被輸入。我在其中得到客戶的地址列表中的控制器的方法(這是我想在文本框中顯示什麼)通過連接到數據庫並執行的LINQ查詢,看起來像下面這樣:在ASP.NET中使用jQuery獲取通過JSON獲取的列表MVC

public ActionResult _getCustomerAddresses(int customerId) 
    { 
     return Json(theShop.getCustomerAddresses(customerId).Select(s => new { AddressID = s.AddressID, Addr = s.FirstName + ": " + s.Address1 }).ToList()); 
    } 

然後我在我的loadAddresses方法的功能而這被當前登錄的用戶的customerID到_getCustomerAddresses方法,看起來像下面我CSHTML文件:

function loadAddresses() { 
    $.ajax({ 
     type: 'post', 
     url: "/ShoppingCart/[email protected]", 
     dataType: "json", 
     success: function (data) { 
      for (var line in data) 
      { 
       //Need to somehow iterate through the data list and append them to an array so I can add them to the source within autocomplete method to display them. 
      } 
     } 
    }); 
} 

我該如何去通過從返回此JSON名單控制器的方法並將它們追加到一個數組來顯示? (jQuery的的.autocomplete功能似乎需要一個數組的數據顯示https://jqueryui.com/autocomplete/)我可能需要使用JSON的一個更好的解釋幫我做這個

非常感謝提前, 科瑞

回答

0

可以使用$.each來循環從Action 返回的所有項首先創建一個空數組,然後推送其中的數據。

function loadAddresses() { 
var itemsSearchItemsArray = new Array(); 
    $.ajax({ 
     type: 'post', 
     url: "/ShoppingCart/[email protected]", 
     dataType: "json", 
     success: function (data) {  
       $.each(data,function(index,value){ 
       itemsSearchItemsArray.push(value.Addr); 
       }); 
     } 
    }); 
} 
0
function loadAddresses() { 
    $.ajax({ 
     type: 'post', 
     url: "/ShoppingCart/[email protected]", 
     dataType: "json", 
     success: function (data) { 
      var myArray = JSON.parse(data.d); 
     } 
    }); 
} 

只需使用JSON.parse來獲得對象的數組。然後你可以簡單地遍歷它,像myArray [0] .AddressID。