Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Ajax in ASP.NET WebForm

2025-01-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use Ajax in ASP.NET WebForm". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use Ajax in ASP.NET WebForm.

For asp.net WebForm projects, there are probably three ways to perform Ajax operations: web services (.asmx files), general handlers (.ashx), and some Ajax controls.

For the ajax control provided by. Net, not to mention the other two ways, you need to introduce additional code files to operate on Ajax (asmx and ashx, and the web service also introduces a cs file corresponding to it). If you want to add some custom Ajax operations to the Example.aspx page, and these Ajax operations will not be used on other pages, you have to introduce additional code files to complete the operation. If the Ajax operation is simple and only needs a simple function to execute, wouldn't it be a troublesome process? In this way, with the increase of Ajax operations in the project, the ashx and asmx files will grow over time, and the maintenance of the project will be doubled. Why can't we put the background code of Ajax operation directly in the Example.aspx.cs file corresponding to Example.aspx? If you can do this, the above two kinds of troubles will be easily solved, won't they?

Therefore, according to the above ideas, the following Ajax framework is implemented. Let's first take a look at the implementation mechanism of this framework:

The image above is a self-drawn abbreviated version of IIS that receives an aspx request from the HttpApplication pipeline and part of the asp.net Page's page life cycle event in executing the ProcessRequest () method. Page itself inherits from the IHttpHandler interface. IHttpHandler provides an important constraint method, ProcessRequest, which specifically handles the received information (HttpContext). Similarly, general handlers and web services also implement their own IHttpHandler and provide some Ajax services. For the specific operation process, please find MSDN yourself.

The principle is that PreInit does some processing at the first event at the beginning of the page life cycle. Once it is found that the hijacked request is an ajax request, then the reflection of C # is used to call the method defined in aspx.cs. After the method is executed, the Response.End () method is called. Calling this method will jump directly to the EndRequest event of the pipeline, thus ending the request, so that there is no need to take some unnecessary steps of the page life cycle. To complete an Ajax operation. If it is found to be a normal operation, then follow the normal process.

Here is a simple example to illustrate the use of the Ajax framework:

1. Add a solution

two。 Create a new Default.aspx page

3. Create a called test method in the Default.aspx.cs page:

Public List TestAjaxMethod (int a, string b, float c) {return new List {a.ToString (), b, c.ToString ()};}

4. Write an Ajax request in Default.aspx

PowerAjax.AsyncAjax ('TestAjaxMethod', [1,2, "333", "sss"], function (SucceessResponse) {/ / successful code})

PowerAjax.js is a simple JS class library encapsulated in Jquery for this framework. There are two main methods in this class library: PowerAjax.AsyncAjax and PowerAjax.SyncAjax. One provides synchronous operation, the other provides asynchronous operation, and has three parameters:

The first argument is the name of the Ajax method that will operate on aspx.cs (using the name reflection method).

The second parameter is an array of parameter list data.

The third parameter is the callback method that is executed after a successful operation, which is the same as the delegate in c#.

Here is the code for this simple JS library:

Var PowerAjax = function () {} PowerAjax.__Private = function () {} / / perform asynchronous operations PowerAjax.AsyncAjax = function (methodName, paramArray, success) {PowerAjax.__Private.Ajax (methodName, paramArray, success, true);} / / synchronous operations PowerAjax.SyncAjax = function (methodName, paramArray, success) {PowerAjax.__Private.Ajax (methodName, paramArray, success, false) } PowerAjax.__Private.Ajax = function (methodName, paramArray, success, isAsync) {var data = {}; switch (paramArray.length) {case 0: data = {'isAjaxRequest': true,' MethodName': methodName}; break; case 1: data = {'isAjaxRequest': true,' MethodName': methodName, "param0": paramArray [0]} Break; case 2: data = {'isAjaxRequest': true,' MethodName': methodName, "param0": paramArray [0], "param1": paramArray [1]}; break Case 3: data = {'isAjaxRequest': true,' MethodName': methodName, "param0": paramArray [0], "param1": paramArray [1], "param2": paramArray [2]}; break Case 4: data = {'isAjaxRequest': true,' MethodName': methodName, "param0": paramArray [0], "param1": paramArray [1], "param2": paramArray [2], "param3": paramArray [3]}; break Case 5: data = {'isAjaxRequest': true,' MethodName': methodName, "param0": paramArray [0], "param1": paramArray [1], "param2": paramArray [2], "param3": paramArray [3], "param4": paramArray [4]}; break;} var url = _ document.location.href $.ajax ({type: "post", url: url, data: data, async: isAsync, datatype: "json", contentType: "application/x-www-form-urlencoded; charset=UTF-8", success: function (response) {success (response) }, error: function (response) {if (response.status = = 500) {var errorMessage = response.responseText; var errorTitle = errorMessage.substring (errorMessage.indexOf (") + 7, errorMessage.indexOf (")) throw new Error ("server internal error:" + errorTitle) });}

5. Change the inheritance page of Default.aspx.cs to AjaxBasePage

Public partial class _ Default: AjaxBasePage

6. Main base class: AjaxBasePage class

The code is as follows:

Public class AjaxBasePage: whether System.Web.UI.Page {/ is an ajax request. / public bool IsAjaxRequest {get; private set;} / if it is an Ajax request, the event of hijacking the PreInit of the page life cycle will be returned directly to Response / protected override void OnPreInit (EventArgs e) {AjaxRequest ajaxRequest = AjaxRequest.GetInstance (Request.Form); this.IsAjaxRequest = ajaxRequest.IsAjaxRequest If (this.IsAjaxRequest) {AjaxApplication ajaxApplication = new AjaxApplication (this, ajaxRequest); ajaxApplication.EndRequest ();} else {/ / if it is not an Ajax request, continue to execute the remaining events in the page life cycle base.OnPreInit (e);}

This class overrides the PreInit method to determine whether the request is an Ajax request. The AjaxRequest class receives and processes the received request, extracting some valid data, such as whether it is an Ajax request, the name of the method, and the parameter list (AjaxParameter class).

As for the AjaxParameter class, the internal data structure is actually a dictionary, and an index is used to provide convenient access to the data, providing a Count attribute to get the number of parameters. The code is as follows

Public class AjaxParameter {private IDictionary m_DictionaryParamsData = new Dictionary (); / returns the number of parameters. / public int Count {get {return this.m_DictionaryParamsData.Count;}} / Index the value of the specific parameter. / public string this [int index] {get {if (index > = 5 | | index

< 0) { throw new NotSupportedException("请求方法的参数的个数限制为:0-5"); } return this.m_DictionaryParamsData[index]; } } public AjaxParameter(IDictionary paramsData) { this.m_DictionaryParamsData = paramsData; } } AjaxRequest类的设计思路其实是模仿HttpContext设计,HttpContext能够从基础的http请求报文分析出以后处理将要用到的数据(response,request,session,cookie等等)数据,而AjaxRequest通过分析Ajax的Post请求的数据域 Data分析出各种以后会用到的数据。如下是该类的代码: public class AjaxRequest { private Dictionary m_DictionaryParamsData = new Dictionary(); private AjaxParameter m_AjaxParameter; private int m_Count = 0; #region 属性 /// /// 是否是一个Ajax请求。 /// public bool IsAjaxRequest { get; private set; } /// /// 请求的方法名字。 /// public string MethodName { get; private set; } /// /// 参数数据。 /// public AjaxParameter Parameters { get { return this.m_AjaxParameter; } } #endregion #region 构造函数 private AjaxRequest(NameValueCollection nameValueCollection) { this.IsAjaxRequest = nameValueCollection["isAjaxRequest"] == "true"; if (this.IsAjaxRequest) { this.MethodName = nameValueCollection["MethodName"]; foreach (string value in nameValueCollection) { string formKey = string.Format("param{0}", this.m_Count); if (nameValueCollection[formKey] != null) { this.m_DictionaryParamsData.Add(this.m_Count, nameValueCollection[formKey]); this.m_Count++; } } m_AjaxParameter = new AjaxParameter(this.m_DictionaryParamsData); } } #endregion #region 实例方法 public static AjaxRequest GetInstance(NameValueCollection nameValueCollection) { return new AjaxRequest(nameValueCollection); } #endregion #region ToString public override string ToString() { return this.MethodName; } #endregion } 通过分析AjaxRequest的属性IsAjaxRequest可判断是否为Ajax请求,若该请求为一个Ajax请求,那么创建一个AjaxApplication实例,在创建AjaxApplication实例的过程中会利用当前页面和AjaxRequest提供的数据进行实际方法的调用(反射),该类是执行Ajax方法的核心类,其中会判断是否读取的到的方法是一个有效的方法,并判断从JS中AjaxApplication传入的参数类型的有效性,目前只提供对以下13中参数提供支持,如下: (String、Boolean、Int32、Int64、UInt32、UInt64、Single、Double、Decimal、DateTime、DateTimeOffset、TimeSpan、Guid) 如果方法中出现非以上类型,将会抛出异常。为了方便Ajax的调试,在JS前段类库中我会对异常进行处理,并抛出Error,Error信息有效的截取了继承自Exception的抛出信息,至于如何获 得更加详细的JS调试信息,以后JS库中可能会做提供更加详细的调用信息,毕竟框架是在改进中进行的。如下是AjaxApplication类的具体代码: public class AjaxApplication { private AjaxBasePage m_AjaxBasePage; private object m_ResponseData; public AjaxApplication(AjaxBasePage ajaxBasePage, AjaxRequest ajaxRequest) { this.m_AjaxBasePage = ajaxBasePage; Type ajaxBasePageType = ajaxBasePage.GetType(); MethodInfo methodInfo = ajaxBasePageType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance) .FirstOrDefault(item =>

Item.Name = = ajaxRequest.MethodName); object [] parameterData = this.GetParameterData (ajaxRequest, methodInfo); if (methodInfo.IsStatic) {this.m_ResponseData = methodInfo.Invoke (null, parameterData);} else {this.m_ResponseData = methodInfo.Invoke (ajaxBasePage, parameterData) } / get parameter data. / / private object [] GetParameterData (AjaxRequest ajaxRequest, MethodInfo methodInfo) {if (methodInfo! = null) {ParameterInfo [] parameterInfos = methodInfo.GetParameters (); if (parameterInfos.Length > 5) {throw new NotSupportedException ("up to 5 parameters") } if (parameterInfos.Length > ajaxRequest.Parameters.Count) {throw new ArgumentException ("missing parameter!");} List parameterData = new List (parameterInfos.Length); for (int I = 0; I < parameterInfos.Length) String paramValue +) {ParameterInfo parameterInfo = parameterInfos [I]; string paramValue = ajaxRequest.Parameters [I]; try {parameterData.Add (ParseAjaxParameter (paramValue, parameterInfo)) } catch (FormatException) {string format = string.Format ("the type of {1} (counting from 0) parameter of the incoming static method {0} does not match, it should be {2} type please check!" , methodInfo.Name, I, parameterInfo.ParameterType.Name); throw new FormatException (format);}} return parameterData.ToArray () } else {throw new InvalidOperationException ("this method was not found, please check the method signature (the method must be public);}} / type conversion. Support String, Boolean, Int32, Int64, UInt32, UInt64, Single, Double, Decimal, DateTime, DateTimeOffset, TimeSpan, Guid / private object ParseAjaxParameter (string ajaxParameterValue, ParameterInfo parameterInfo) {object obj; if (parameterInfo.ParameterType = = typeof (String)) {obj = ajaxParameterValue } else if (parameterInfo.ParameterType = = typeof (Boolean)) {obj = bool.Parse (ajaxParameterValue);} else if (parameterInfo.ParameterType = = typeof (Int32)) {obj = Int32.Parse (ajaxParameterValue) } else if (parameterInfo.ParameterType = = typeof (UInt32)) {obj = UInt32.Parse (ajaxParameterValue);} else if (parameterInfo.ParameterType = = typeof (UInt64)) {obj = UInt64.Parse (ajaxParameterValue) } else if (parameterInfo.ParameterType = = typeof (Single)) {obj = Single.Parse (ajaxParameterValue);} else if (parameterInfo.ParameterType = = typeof (Double)) {obj = Double.Parse (ajaxParameterValue) } else if (parameterInfo.ParameterType = = typeof (Decimal)) {obj = Decimal.Parse (ajaxParameterValue);} else if (parameterInfo.ParameterType = = typeof (DateTime)) {obj = DateTime.Parse (ajaxParameterValue) } else if (parameterInfo.ParameterType = = typeof (DateTimeOffset)) {obj = DateTimeOffset.Parse (ajaxParameterValue);} else if (parameterInfo.ParameterType = = typeof (TimeSpan)) {obj = TimeSpan.Parse (ajaxParameterValue) } else if (parameterInfo.ParameterType = = typeof (Guid)) {obj = Guid.Parse (ajaxParameterValue);} else {throw new NotSupportedException ("method parameter type is not supported!") ;} return obj;} / ends the page life cycle while executing the EndRequest event of the application life cycle directly. / / public void EndRequest () {HttpResponse response = this.m_AjaxBasePage.Page.Response; response.ContentType = "application/json"; response.Clear (); JavaScriptSerializer jsonSerializer2 = new JavaScriptSerializer (); response.Write (jsonSerializer2.Serialize (new JsonResponse {IsSuccess = true, Message = "processed successfully", ResponseData = this.m_ResponseData})) Response.End ();}}

After initializing an AjaxApplication instance, you can call the instance's EndRequest () method to end the Ajax request. The Response.End () method is finally called inside the method to end the page life cycle and most of the pipeline events.

And use the JsonResponse class to encapsulate the returned data.

Public class JsonResponse {public bool IsSuccess {get; set;} public string Message {get; set;} public object ResponseData {get; set;}}

The last parameter of this class carries the return value of the calling method, which is an Object type, that is, the framework can support any type of return value, which can of course be serialized.

7. Looking back at the Ajax request, you can use the following for the return value:

PowerAjax.AsyncAjax ('TestAjaxMethod', [1,2, "333", "sss"], function (SucceessResponse) {if (SucceessResponse.IsSuceess) {alert ("Congratulations, the ajax method call succeeded!") ; Process (SucceessResponse.ResponseData); / / you may need to implement the returned data here, because I can't tell what you want to return. This is an Object} else {alert ("this is an operation error, not an internal exception, which I will handle internally!") ; alert ("error message:" + SucceessResponse.Message);}}) Thank you for reading, the above is the content of "how to use Ajax in ASP.NET WebForm". After the study of this article, I believe you have a deeper understanding of how to use Ajax in ASP.NET WebForm, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report