2012-12-10 57 views
3

我使用X-Editable Plugin在Asp.net。
我已經試過這樣:Usage with .Net and C# Webmethods
但它給我的錯誤。它並不像它應該那樣調用WebMethod。X編輯與.NET和C#Web方法

如何解決這個問題?
請幫忙。

的Javascript:

$('#username').editable({ 
    url: function (params) {      
     return $.ajax({ 
      url: 'Default.aspx/TestMethod', 
      data: JSON.stringify(params), 
      dataType: 'json', 
      async: true, 
      cache: false, 
      timeout: 10000, 
      success: function (response) { 
        alert("Success"); 
      }, 
      error: function() { 
        alert("Error in Ajax"); 
      } 
      }); 
     } 
}); 

HTML:

<a href="#" id="username" class="myeditable">superuser</a> 

的WebMethod Default.aspx中:

[System.Web.Services.WebMethod] 
public static String TestMethod(String params) 
{ 
    //access params here 
} 

回答

5

如果你想調用一個頁面的方法,首先你需要請求類型POST(也有內容類型設置不會做任何危害):

$('#username').editable({ 
    url: function (params) {      
     return $.ajax({ 
      type: 'POST', 
      url: 'Default.aspx/TestMethod', 
      data: JSON.stringify(params), 
      contentType: 'application/json; charset=utf-8', 
      dataType: 'json', 
      async: true, 
      cache: false, 
      timeout: 10000, 
      success: function (response) { 
       alert("Success"); 
      }, 
      error: function() { 
       alert("Error in Ajax"); 
      } 
     }); 
    } 
}); 

另外,JSON會自動反序列化服務器端,所以你應該期望在服務器端namepkvalue參數(這就是插件根據docs

[System.Web.Services.WebMethod] 
public static String TestMethod(string name, string pk, string value) 
{ 
    //access params here 
} 
發送

在你的情況pk將是空的,你沒有設置一個。

+0

謝謝tpeczek。我沒有提供用於Ajax調用的TYPE。也感謝WebMehthod的簽名。 –

+0

+1順便說一句我可以使用PUT嗎?由於PUT是爲了'更新'而POST是'添加新的'。我在這裏使用REST方法。 – Roylee

+1

@Roylee恐怕沒有辦法在ASP.NET端更改支持的動詞,您必須改爲使用HttpHandler。 – tpeczek