我们都知道在AjaxPro的方法AjaxPro.Utility.RegisterTypeForAjax(typeof(所在类的类名));会将标记有[Ajax.AjaxMethod]方法注册在客户端。在某项目中,设计模板字段引擎,采用html+jquery实现,这里的数据就难免需要ajax获取,但是团队对于js掌握不一,所以我写了下面辅助类,可以像ajaxpro一样简化ajax的开发。
代码-jQueryInvokeMethodAttribute (此处只做标示方法处理,所以为空):
[AttributeUsage(AttributeTargets.Method, AllowMultiple=
false,Inherited=
false)]
public class jQueryInvokeMethodAttribute : Attribute
{
}
public class jQueryInvokeMethodAttribute : Attribute
{
}
代码-jQueryAjaxUtility(分注册脚本和调用ajax事件):
View Code
为了考虑反射的性能,加入了类级注册脚本方法缓存处理jQueryUtilityCache,具体见demo。
测试:
html:
<
form
id
="form1"
runat
="server"
>
< div >
< input id ="Button1" type ="button" value ="button" />
</ div >
</ form >
< div >
< input id ="Button1" type ="button" value ="button" />
</ div >
</ form >
后台方法注册Page_Load
Green.Utility.jQueryAjaxUtility.RegisterClientAjaxScript(
typeof(_Default));
1:
前台:
_Default.Test("ajax",
{
success: function(e) {
alert(e);
},
dataType: "text"
});
{
success: function(e) {
alert(e);
},
dataType: "text"
});
后台:
[Green.Utility.jQueryInvokeMethod()]
public static string Test( string str)
{
return " hello: " + str;
}
public static string Test( string str)
{
return " hello: " + str;
}
效果:
2:
前台ajax:
_Default.TestArrayJson(1, 2, 3,
{
success: function(e) {
$.each(e, function(i, n) { alert(n); });
},
dataType: "json"
})
{
success: function(e) {
$.each(e, function(i, n) { alert(n); });
},
dataType: "json"
})
后台:
[Green.Utility.jQueryInvokeMethod()]
public static int[] TestArrayJson( int p1, int p2, int p3)
{
return new int[] { p1, p2, p3 };
}
public static int[] TestArrayJson( int p1, int p2, int p3)
{
return new int[] { p1, p2, p3 };
}
效果:
3:
前台ajax:
_Default.TestArrayxml("key", "value",
{
success: function(e) {
alert(e.key);
alert(e.Value);
},
dataType: "json"
})
{
success: function(e) {
alert(e.key);
alert(e.Value);
},
dataType: "json"
})
后台:
[Green.Utility.jQueryInvokeMethod()]
public static Test TestArrayxml( string key, string value)
{
return new Test() { key=key,Value=value};
}
public static Test TestArrayxml( string key, string value)
{
return new Test() { key=key,Value=value};
}
效果:
最后看看FireBug中ajax http头信息:
其他资料jQuery目录: 我jQuery系列之目录汇总
附录:代码下载
本文转自破狼博客园博客,原文链接:http://www.cnblogs.com/whitewolf/archive/2011/09/26/2192253.html,如需转载请自行联系原作者