2015-01-13 35 views
0

enter image description here我创建了一个web方法,现在我在我的java脚本文件中调用了它,但它给出了一个路径错误,它无法找到我要给的路径..C#Web方法不在javascript中调用

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#方法类,但它不工作给出一个错误缺点ole,任何人都可以建议我什么,我在这里失踪..

+0

从URL路径删除第一个斜杠(/)的Ajax和尝试 –

+0

试过,解决不了我的问题 –

+0

视图文件夹在sitecore文件夹中有什么? –

回答

10

阿贾克斯有几个规则与asp.net工作。

  • 你的WebMethod应该是publicstatic
  • 如果您的WebMethod预期某些参数(s)比这些参数必须在ajax中以data的形式传递。
  • 参数名称应该是same,WebMethoddata部分的ajax。
  • 从ajax传来的数据应该在json string。为此,您可以使用JSON.stringify或者您将不得不围绕quotes中的参数values

如果您在使用AJAX比GET您需要启用的webmethod从GET请求来调用请检查下面的示例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<string> CallAjax(string name,int value) 
{ 
    List<string> list = new List<string>(); 
    try 
    { 
     list.Add("Mairaj"); 
     list.Add("Ahmad"); 
     list.Add("Minhas"); 
    } 

    catch (Exception ex) 
    { 

    } 

    return list; 
} 

编辑

。在WebMetod

的顶部添加 [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
[System.Web.Services.WebMethod] 
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)] 
public static int ItemCount() 
+0

我的网页在一个文件夹内那么我需要添加它是不是我在URL中或不是 –

+0

不,它是找到页面,但你需要使WebMethod静态。 – Mairaj

+0

我得到同样的错误,而我改变方法为静态 –

0

只需修改相应的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; 
}