In a project, the Design template field engine, using the Html+jquery implementation, where the data will inevitably need Ajax access, but the team for JS Master, so I wrote the following auxiliary class, can be like Ajaxpro to simplify the development of Ajax.
Code-jqueryinvokemethodattribute (here is only marked method processing, so null):
Copy Code code as follows:
[AttributeUsage (AttributeTargets.Method, Allowmultiple=false,inherited=false)]
public class Jqueryinvokemethodattribute:attribute
{
}
Code-jqueryajaxutility (sub-registration scripts and invoke AJAX events):
Copy Code code as follows:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Namespace Green.utility
{
public class Jqueryajaxutility
{
public static string Ajaxinvokeparam = "Ajaxinvoke";
public static string ajaxinvokevalue = "1";
public static string responsecharset = "UTF-8";
protected static System.Web.UI.Page Page
{
Get
{
return System.Web.HttpContext.Current.Handler as System.Web.UI.Page;
}
}
public static void Registerclientajaxscript (type type)
{
if (Page!= null)
{
if (system.web.httpcontext.current.request[ajaxinvokeparam] = = Ajaxinvokevalue)
{
Registerajaxinvokeevent (type);
}
Else
{
Registerajaxinvokescript (type);
}
}
}
protected static void Registerajaxinvokescript (type type)
{
Page.ClientScript.RegisterClientScriptBlock (type. GetType (), type. GetType (). FullName + "_" + typeof (Jqueryajaxutility). FullName + "_ajaxinvokedefaultoption", "Window.defaultajaxoption={type: ' Get ', Cache:false, DataType: ' Text '};", true) ;
if (!jqueryutilitycache.current.exists (type))
{
var methodinfo = type. GetMethods (System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public). Where (t =>
{
var attrs = T.getcustomattributes (typeof (Jqueryinvokemethodattribute), false);
if (attrs!= null && attrs. Length > 0)
return true;
return false;
}). ToList ();
if (MethodInfo!= null && methodinfo. Count > 0)
{
System.Text.StringBuilder sb = new StringBuilder ();
Sb. AppendFormat ("window.{ 0}=function () {{}}; ", type. Name);
MethodInfo. ForEach (t =>
{
var parameters = T.getparameters (). Select (P => p.name). ToArray ();
Sb. AppendFormat ("{2}.{ 0} = function ({1} ajaxoption) {{", t.name, parameters. Count () > 0? String. Join (",", parameters) + ",": ", type. Name);
Sb. Append ("If" (ajaxoption==null| | typeof ajaxoption== ' undefined ') {ajaxoption={};}; ");
var url = Page.Request.RawUrl.IndexOf ("?") = = 1? Page.Request.RawUrl:Page.Request.RawUrl.Substring (0, Page.Request.RawUrl.IndexOf ("?"));
Sb. AppendFormat ("Ajaxoption.url = ' {0} ';", url);
var data = "'";
if (parameters. Count () > 0)
{
data = (string. Join ("", Parameters. Select (P => string. Format ("' &{0}= ' + {0}+", p)). ToArray ()));
Data= data. TrimEnd (' + ');
}
Sb. AppendFormat ("Ajaxoption.data = ' method={1}&rn={4}&{2}={3} ' +{0};", data, T.name, Ajaxinvokeparam, Ajaxinvokevalue,guid.newguid (). ToString ());
Sb. Append ("ajaxoption= jquery.extend (window.defaultajaxoption,ajaxoption);");
Sb. Append ("Jquery.ajax (ajaxoption);};");
});
JQueryUtilityCache.Current.AddScript (Type, sb.) ToString ());
}
}
var script = JQueryUtilityCache.Current.GetScript (type);
Page.ClientScript.RegisterClientScriptBlock (type. GetType (), type. GetType (). FullName + "_" + typeof (Jqueryajaxutility). FullName + "_ajaxinvoke", script, True);
}
Protected string Genertorscript (type type)
{
return string. Empty;
}
protected static void Registerajaxinvokeevent (type type)
{
var Request = System.Web.HttpContext.Current.Request;
var Response = System.Web.HttpContext.Current.Response;
var method = Request[' method '];
if (string. IsNullOrEmpty (method))
Return
Response.Clear ();
var methodinfo = type. GetMethod (method, System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
if (MethodInfo!= null)
{
Response.Charset = Responsecharset;
Response.ContentType = string. Join (",", request.accepttypes);
var param = MethodInfo. GetParameters ();
object[] Objs = new Object[param. Length];
var i = 0;
Param. ToList (). ForEach (t =>
{
objs[i++] = Convert.changetype (Request[t.name], t.parametertype);
});
var obj = MethodInfo. Invoke (null, OBJS);
if (obj!= null)
{
Serialization of
if (!obj. GetType (). Isvaluetype && obj. GetType ()!= typeof (String))
{
if (Request.AcceptTypes.Contains ("Text/xml"))
{
Response.Write (Green.Utility.SerializerUtility.XmlSerializer (obj));
}
else if (Request.AcceptTypes.Contains ("Application/json"))
{
Response.ContentType = "Application/json, Text/javascript, */*";
Response.Write (Green.Utility.SerializerUtility.JsonSerializer (obj));
}
Else
{
Response.Write (obj);
}
}
Else
{
Response.Write (obj);
}
}
Response.Flush ();
Response.close ();
Response.End ();
}
}
}
}
In order to consider the performance of reflection, the class-level registration script method is added to the cache processing Jqueryutilitycache, specifically see demo.
Test:
Html:
Copy Code code as follows:
<form id= "Form1" runat= "Server" >
<div>
<input id= "Button1" type= "button" value= "button"/>
</div>
</form>
Background method Registration Page_Load
Copy Code code as follows:
Green.Utility.jQueryAjaxUtility.RegisterClientAjaxScript (typeof (_default));
1:
Front desk:
Copy Code code as follows:
_default.test ("Ajax",
{
Success:function (e) {
Alert (e);
},
DataType: "Text"
});
Background:
Copy Code code as follows:
[Green.Utility.jQueryInvokeMethod ()]
public static string Test (String str)
{
Return "Hello:" + str;
}
Effect:
2: Foreground Ajax:
Copy Code code as follows:
_default.testarrayjson (1, 2, 3,
{
Success:function (e) {
$.each (E, function (i, N) {alert (n);});
},
DataType: "JSON"
})
Background:
Copy Code code as follows:
[Green.Utility.jQueryInvokeMethod ()]
public static int[] Testarrayjson (int p1, int p2, int p3)
{
return new int[] {p1, p2, p3};
}
Effect:
3: Foreground Ajax:
Copy Code code as follows:
_default.testarrayxml ("Key", "value"),
{
Success:function (e) {
alert (E.key);
alert (E.value);
},
DataType: "JSON"
})
Background:
Copy Code code as follows:
[Green.Utility.jQueryInvokeMethod ()]
public static Test Testarrayxml (string key,string value)
{
return new Test () {key=key,value=value};
}
Effect:
Finally look at the Ajax HTTP header information in Firebug:
Appendix: Code Downloads
Author: Wolf (Cnblogs)