小编典典

C# Web method is not calling in javascript

c#

enter image description herei create a
web method and now i’m calling this in my java script file but it give an path
error,it is not able to find path what i’m giving ..

Web method code is :

    [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 script function calling like as:

    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;}

while i’m giving exact path for the C# method class but it’s not working give
an error on console, can anyone suggest me what i’m missing here..


阅读 309

收藏
2020-05-19

共1个答案

小编典典

There are few rules for ajax to work with asp.net.

  • Your WebMethod should be public and static.
  • If your WebMethod expects some parameter(s) than these parameter(s) must
    be passed as data in ajax.
  • Name of parameter(s) should be same in WebMethod and in data part
    of ajax.
  • Data passed from ajax should be in json string.For this you can use
    JSON.stringify or you will have to surround the values of parameter(s)
    in quotes.

Please check the below sample ajax call

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;
}

EDIT

If you use GET in ajax than you need to enable your webmethod to be called
from GET request. Add [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)] on top of WebMetod

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