C#Web方法不是在javascript中调用

在此处输入图像描述 我创建一个Web方法,现在我在我的java脚本文件中调用它,但它给出了路径错误,它无法找到我给的路径..

Web方法代码是:

[System.Web.Services.WebMethod] public static int ItemCount(string itemId) { int val = 0; Item itm = Sitecore.Context.Database.GetItem(itemId); val = itm.Children.Count; return val; } 

java脚本函数调用如:

  function GetItemCount(itemId) { var funRes = ""; debugger; try { if (itemId != null) { jQuery.ajax({ cache: false, type: "POST", contentType: "application/json; charset=utf-8", url: "/Views/GetItem.aspx/ItemCount", data: { itemId: itemId }, dataType: "json", async: false, success: function (data) { funRes = data.result; }, error: function(err) { alert(err.responseText); } }); } } catch (ex) { alert(ex.message); } return funRes;} 

虽然我给C#方法类提供了确切的路径,但它不起作用在控制台上出错,有人能建议我在这里缺少什么..

ajax与asp.net一起使用的规则很少。

  • 您的WebMethod应该是publicstatic
  • 如果您的WebMethod需要一些参数,那么这些参数必须作为ajax中的data传递。
  • 参数名称在WebMethod和ajax的data部分中应该same
  • 从ajax传递的数据应该是json string 。为此你可以使用JSON.stringify或者你必须用quotes起参数的values

请检查以下示例ajax调用

 function CallAjax() { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "Default.aspx/CallAjax", data: JSON.stringify({ name: "Mairaj", value: "12" }), dataType: "json", async: false, success: function (data) { //your code }, error: function (err) { alert(err.responseText); } }); } [WebMethod] public static List CallAjax(string name,int value) { List list = new List(); try { list.Add("Mairaj"); list.Add("Ahmad"); list.Add("Minhas"); } catch (Exception ex) { } return list; } 

编辑

如果你在ajax中使用GET而不是你需要从GET请求调用webmethod。 在[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]添加[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]

 [System.Web.Services.WebMethod] [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)] public static int ItemCount() 

只需修改javascript函数,如下所示

  function GetItemCount(itemId) { var funRes = ""; debugger; try { if (itemId != null) { jQuery.ajax({ type: "GET", url: "/Views/GetItem.aspx", data: 'itemID=' + itemId, contentType: "application/html", dataType: "html", success: function (response) { funRes= response.result; } }); } } catch (ex) { alert(ex.message); } return funRes; }