簡體   English   中英

從asp.net中的實體框架對象返回數據到jquery/ajax調用

[英]Return data to jquery/ajax call from entity framework object in asp.net

我正在嘗試使用 jquery/ajax 調用從實體框架中獲取List<Product> 這是ajax請求。

$.ajax({
            type: "POST",
            url: "searchService.asmx/search",
            data: "{'lookup':'itemName'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (products) {
                // Just printing the result for now.
                console.log(products);
            }
        });

Web服務中的搜索方法實現為:

[WebMethod]
public List<Product> search(string lookup)
{
    using (eCommerceDBEntities context = new eCommerceDBEntities())
    {
        List<Product> pr = context.Products.Where(i => i.ProductName.Contains(lookup)).ToList();
        return pr;
    }
}

出於某種原因,我在控制台日志中收到了 500(內部服務器錯誤)。

令我驚訝的是,以下代碼有效:

[WebMethod]
public List<Product> search(string lookup)
{
    using (eCommerceDBEntities context = new eCommerceDBEntities())
    {
        List<Product> pr = context.Products.Where(i => i.ProductName.Contains(lookup)).ToList();
        return new List<Product> {new Product(){
            ProductName="abc", ProductPrice=123},
            new Product(){
                ProductName ="xyz", ProductPrice=321
            }
        };
    }
}

上面硬編碼的List<Product>返回一個不錯的對象,但我從數據庫查詢的對象沒有。 我會假設它是硬編碼的還是查詢形式的數據庫都是一樣的。

我是第一次嘗試這種方法,所以我可能在這里做錯了什么。 如何從數據庫獲取數據?

如果你得到 500 看起來你在服務器端有一些例外。 你能找出異常發生的地方以及你得到了什么堆棧跟蹤嗎? 嘗試檢查Productcontext.Products之間的類型兼容性。

List<Product> pr = context.Products.Where(i => i.ProductName.Contains(lookup)).ToList();

您也可以從客戶端檢查lookup值以進行正確解析。

public List<Product> search(string lookup)

並且包含()用於有效變量。

i => i.ProductName.Contains(lookup)

嘗試在您的網絡方法上使用這些屬性。

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

它應該工作。

您還需要檢查 lambda 表達式的輸出。

編輯 -1

由於您的服務以字符串為參數,因此將contentType更改為字符串並檢查。
您還可以從 jQuery ajax 調用中刪除它。

$.ajax({
        type: "POST",
        url: "searchService.asmx/search",
        data: "{'lookup':'itemName'}",
        //contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (products) {
            // Just printing the result for now.
            console.log(products);
          }
      });

暫無
暫無

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

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