C# Web method is not calling in javascript

C# Web method is not calling in javascript,第1张

C# Web method is not calling in javascript

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 pre }, 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()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5487528.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存