Ami*_*rma 0 javascript c# asp.net-mvc jquery 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;
}
Run Code Online (Sandbox Code Playgroud)
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;}
Run Code Online (Sandbox Code Playgroud)
虽然我给C#方法类提供了确切的路径,但它没有工作在控制台上给出错误,任何人都可以建议我在这里缺少什么..
Mai*_*mad 12
ajax与asp.net一起使用的规则很少.
- 你的WebMethod应该是
public
和static
.- 如果您的WebMethod需要一些参数,那么必须像
data
在ajax中那样传递这些参数.- 参数(S)的名称应该是
same
在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;
}
Run Code Online (Sandbox Code Playgroud)
编辑
如果您GET
在ajax中使用,则需要启用从GET
请求调用webmethod .添加[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
在WebMetod之上
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static int ItemCount()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3760 次 |
最近记录: |