C#Web方法是在JavaScript调用 [英] C# Web method is not calling in javascript
问题描述
我创建了一个Web方法,现在我在我的Java脚本文件调用此但它给出的路径错误,是不是能找到什么路我给..
i 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方法code是:
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脚本函数调用类似如下:
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;}
而我给确切路径为C#方法类,但它不工作在控制台上给出一个错误,任何人都可以建议我什么,我在这里失踪。
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..
推荐答案
有阿贾克斯与asp.net工作规则等等。
There are few rules for ajax to work with asp.net.
- 您的WebMethod应
公共
和静态
。 - 如果您的WebMethod预计一些比这些参数(s)参数(S)必须为
在AJAX数据
传递。 - 参数(S)的名称应为
同
在的WebMethod
和数据
AJAX的一部分。 - 数据从阿贾克斯传递应该在
JSON字符串
。为此,你可以使用JSON.stringify
或你会有包围报价参数(S)的
。值
- Your WebMethod should be
public
andstatic
.- 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
inWebMethod
and indata
part of ajax.- Data passed from ajax should be in
json string
.For this you can useJSON.stringify
or you will have to surround thevalues
of parameter(s) inquotes
.
请检查下面的示例Ajax调用
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;
}
修改
如果您使用 GET
在阿贾克斯比你需要启用的webmethod是从 GET
请求来调用。添加 [System.Web.Script.Services.ScriptMethod(UseHttpGet = TRUE)]
上WebMetod顶部
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()
这篇关于C#Web方法是在JavaScript调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!