小编典典

C#Web方法未在JavaScript中调用

json

在此处输入图片说明我创建了一个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#方法类提供了确切的路径,但是它无法正常工作,但在控制台上却给出了一个错误,有人可以建议我在这里缺少什么吗。


阅读 240

收藏
2020-07-27

共1个答案

小编典典

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

  • 您的WebMethod应该为publicstatic
  • 如果您的WebMethod期望某些参数,则必须像data在ajax中一样传递这些参数。
  • 参数名称应same在ajax中,WebMethod且应在data其中。
  • 从ajax传递的数据应该在中json string。为此,您可以使用,JSON.stringify否则您必须将values参数的包围在中quotes

请检查以下示例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;
}

编辑

如果GET在ajax中使用,则需要启用从GET请求中调用Web方法。[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]在WebMetod上添加

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