2014-09-23 25 views
0

我從[WebMethod]返回List<strings>。但是當發生異常時如何將消息返回給AJAX調用者?現在我得到構建錯誤。如何從webmethod將異常返回到AJAX調用?

JS:

$.ajax({ 
    type: 'POST', 
    contentType: "application/json; charset=utf-8", 
    url: 'new.aspx/GetPrevious', 
    data: "{'name':'" + username + "'}", 
    async: false, 
    success: function (data) { 
     Previous = data.d; 
     alert(salts); 
    }, 
    error: function() { 
     alert("Error"); 
    } 
}); 

C#:

[WebMethod] 
public static List<string> GetPreviousSaltsAndHashes(string name) 
{ 
    try 
    { 
     List<string> prevSalts = new List<string>(); 
     if (reader.HasRows) 
     { 
      while (reader.Read()) 
      {      
       prevSalts.Add(reader.GetString(0)); 
      } 
     } 
     conn.Close(); 
     return prevSalts; 
    } 
    catch (Exception ex) 
    { 
     return "failure"; //error showing here 
    } 
} 

回答

0

確保您在這兩種情況下返回相同的類型。你的失敗更改到一個列表:

List<string> prevSalts = new List<string>(); 
try 
{ 
    ... 
} 
catch (Exception ex) 
{ 
    prevSalts.Clear(); 
    prevSalts.Add("failure");  
} 
return Json(new 
{ 
    salts = prevSalts 
}, JsonRequestBehavior.AllowGet); 

編輯:讓你的琴絃在前端,檢查它在適當的方法

success: function (data) { 
    Previous = data.salts 
    alert(salts); 
}, 
error: function (data) { 
    $.each(data.salts, function(index,item) { 
     alert(item); 
    }); 
} 
+0

但是我怎樣才能捕捉錯誤:函數()在AJAX? – James123 2014-09-23 19:18:44

+0

看到我的新編輯 – 2014-09-23 23:49:19

2

所有異常從WebMethod扔得到自動序列化到響應作爲.NET Exception實例的JSON表示。您可以結賬following article瞭解更多詳情。

所以,你的服務器端代碼可能有點簡單:

[WebMethod] 
public static List<string> GetPreviousSaltsAndHashes(string name) 
{ 
    List<string> prevSalts = new List<string>(); 

    // Note: This totally sticks. It's unclear what this reader instance is but if it is a 
    // SqlReader, as it name suggests, it should probably be wrapped in a using statement 
    if (reader.HasRows) 
    { 
     while (reader.Read()) 
     {      
      prevSalts.Add(reader.GetString(0)); 
     } 
    } 

    // Note: This totally sticks. It's unclear what this conn instance is but if it is a 
    // SqlConnection, as it name suggests, it should probably be wrapped in a using statement 
    conn.Close(); 

     return prevSalts; 
    } 
} 

,並在客戶端:

error: function (xhr, status, error) { 
    var exception = JSON.parse(xhr.responseText); 
    // exception will contain all the details you might need. For example you could 
    // show the exception Message property 
    alert(exception.Message); 
} 

,並在一天結束的時候,他說這一切的東西后,你應該意識到WebMethods是一種完全過時和過時的技術,除非您維護一些現有的代碼,否則絕對沒有理由在新項目中使用它們。

0

您可以返回一個通用結構體(實際數據),狀態碼和錯誤字段來描述異常(如果有的話)。然後在JS方面,你只需要根據狀態碼使用正文或錯誤字段。這是我在我最後一次使用soap webservice中使用的。

相關問題