JQuery Ajax-like AjaxPro. Utility. RegisterTypeForAjax-assisted Method

Source: Internet
Author: User

In a project, the template FIELD engine is designed and implemented using html + jquery. The data here will inevitably need to be obtained through ajax, but the Team has different knowledge about js, so I wrote the following auxiliary classes, it can simplify ajax development like ajaxpro.
Code-jQueryInvokeMethodAttribute (the label method is used only here, so it is null ):
Copy codeThe Code is as follows:
[AttributeUsage (AttributeTargets. Method, AllowMultiple = false, Inherited = false)]
Public class jQueryInvokeMethodAttribute: Attribute
{
}

Code-jQueryAjaxUtility (subscribe scripts and call ajax events ):
Copy codeThe Code is 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
{
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 (jqueryinvokemethodattrites), 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
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 reflection performance, the jQueryUtilityCache is added to the class-level registration script method cache. For details, see the demo.
Test:
Html:
Copy codeThe Code is as follows:
<Form id = "form1" runat = "server">
<Div>
<Input id = "Button1" type = "button" value = "button"/>
</Div>
</Form>

Register Page_Load using the background Method
Copy codeThe Code is as follows:
Green. Utility. jQueryAjaxUtility. RegisterClientAjaxScript (typeof (_ Default ));

1:
Front-end:
Copy codeThe Code is as follows:
_ Default. Test ("ajax ",
{
Success: function (e ){
Alert (e );
},
DataType: "text"
});

Background:
Copy codeThe Code is as follows:
[Green. Utility. jQueryInvokeMethod ()]
Public static string Test (string str)
{
Return "hello:" + str;
}

Effect:


2: front-end ajax:
Copy codeThe Code is as follows:
_ Default. TestArrayJson (1, 2, 3,
{
Success: function (e ){
$. Each (e, function (I, n) {alert (n );});
},
DataType: "json"
})

Background:
Copy codeThe Code is as follows:
[Green. Utility. jQueryInvokeMethod ()]
Public static int [] TestArrayJson (int p1, int p2, int p3)
{
Return new int [] {p1, p2, p3 };
}

Effect:

 
3: front-end ajax:
Copy codeThe Code is as follows:
_ Default. TestArrayxml ("key", "value ",
{
Success: function (e ){
Alert (e. key );
Alert (e. Value );
},
DataType: "json"
})

Background:
Copy codeThe Code is as follows:
[Green. Utility. jQueryInvokeMethod ()]
Public static Test TestArrayxml (string key, string value)
{
Return new Test () {key = key, Value = value };
}

Effect:

Finally, let's take a look at the ajax http header information in FireBug:


Appendix: Code download
Author: cnblogs)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.