Home>Article>Web Front-end> Using Ajax under ASP.NET
Previously, I introduced the preliminary understanding of Ajax inUnderstanding Ajax. This article will introduce how to use it conveniently in ASP.NET Ajax, the first one is of course using jQuery's ajax, which is powerful and easy to operate. The second one is to use .NET encapsulated ScriptManager.
Related free learning recommendations:ajax(Video)
This is the simplest way. First, briefly understand the syntax of jQuery ajax. The most commonly used calling method is this: $.ajax({settings}) ; There are several commonly used settings. All parameters and their explanations can be found in jQuery official API documentation
1. type: request method get/post
2. url: requested Uri
3. async: whether the request is asynchronous
4. headers: customized header parameters
5. data: parameters sent to the server
6. dataType: Parameter format, common ones include string, json, xml, etc.
7. contents: A "string/regular expression" map that determines how to parse the response
8. contentType: Send The content encoding type of the data sent to the server. Its default value is "application/x-www-form-urlencoded; charset=UTF-8".
9. success: The handle called after the request is successful.
10.error: The handle called after the request fails
If you haven’t used jQuery’s ajax before, it feels a bit confusing. Let’s take a look at a simple example
First use Visual Studio to create a new WebApplication, introduce jQuery.js into the project, and then add two pages, Default.aspx as a test
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Web.Default" %>Ajax
NormalPage.aspx is used as the request page, no processing is done first. In the JavaScript in the Default.aspx page, you can see that the testGet function uses jQuery Ajax sends a get request to Normal.aspx. The unwritten parameters use jQuery default parameters. This call does not use any parameters. It simply sends a request to the Normal.aspx page. If the request is successful, all responses will be alerted (that is, the success method parameters: result, jQuery will pass the responseText into the success method as the first parameter), and if the request fails, a line of error text will be added to p. If everything is normal, you can see a dialog box popping up on the page, and the content in the dialog box is the Normal.aspx page Content
A simple get request is completed. Such results are generally of little use and are not the intention of ajax. The main purpose of using Ajax is to use JavaScript to send asynchronously to the server. Specific requests to obtain server-related data, such as asking the server for weather, then obtaining weather data, updating the page, rather than obtaining the entire page. In other words, using Ajax itself is to get rid of the pattern of updating the entire page to update page data, just We only need the server to give us data, which requires calling a specific method on the server side.
We need to modify NormalPage.aspx at this time and add several methods to it for Default.aspx test call
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace Web { public partial class NormalPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string action = Request.QueryString["action"]; Response.Clear(); //清除所有之前生成的Response内容 if (!string.IsNullOrEmpty(action)) { switch (action) { case "getTime": Response.Write(GetTime()); break; case "getDate": Response.Write(GetDate()); break; } } Response.End(); //停止Response后续写入动作,保证Response内只有我们写入内容 } private string GetDate() { return DateTime.Now.ToShortDateString(); } private string GetTime() { return DateTime.Now.ToShortTimeString(); } } }
Then add a new method to Default.aspx and modify the button’s onclick method to the newly written function
function testGet2() { $.ajax({ type: 'get', url: 'NormalPage.aspx', async: true, data:{action:'getTime'}, success: function (result) { setContainer(result); }, error: function () { setContainer('ERROR!'); } }); }
The testGet2 function is in Some modifications were made based on the testGet function. First, the success method was changed and the obtained response was written to the page; then the data parameter was added to the request, and the request sent an action: getTime key-value pair to the server. In get In the request, jQuery will convert this parameter into a url parameter. The above writing method has the same effect as this writing method
function testGet3() { $.ajax({ type: 'get', url: 'NormalPage.aspx?action=getTime', async: true, success: function (result) { setContainer(result); }, error: function () { setContainer('ERROR!'); } }); }
Look at the execution effect, this is the monitoring result of Chrome
如果调试我们发现这个请求调用的服务器页面NormalPage.aspx的GETime方法,并且response中只包含对有用的数据,如果把请求中参数的值改为getDate,那么就会调用对应GetDate方法。
这样向一个页面发送请求然后在Load事件处理程序中根据参数调用不同方法,清除Response,写入Response,终止Response,而且传入的参数局限性太大,好业余的赶脚,看看专业些解决方法。为project添加一个General Handler类型文件,关于HttpHandler相关内容本文不做详细解释,只需知道它可以非常轻量级的处理HTTP请求,不用走繁琐的页面生命周期处理各种非必需数据。
Handler.ashx.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;using Newtonsoft.Json;namespace Web { ////// Summary description for Handler /// public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { Student stu = new Student(); int Id = Convert.ToInt32(context.Request.Form["ID"]); if (Id == 1) { stu.Name = "Byron"; } else { stu.Name = "Frank"; } string stuJsonString= JsonConvert.SerializeObject(stu); context.Response.Write(stuJsonString); } public bool IsReusable { get { return false; } } } }
关于这个类语法本文不做详细说明,每次发起HTTP请求ProcessRequest方法都会被调用到,Post类型请求参数和一再Request对象的Form中取得,每次根据参数ID值返回对应json对象字符串,为了展示json格式数据交互,需要为项目引入json.net这一开源类库处理对象序列化反序列化问题,然后创建一个Student类文件
Student.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Web { public class Student { public int ID { get; set; } public string Name { get; set; } } }
看看页面如何处理
function testPost() { $.ajax({ type: 'post', url: 'Handler.ashx', async: true, data: { ID: '1' }, success: function (result) { setContainer(result); var stu =eval ('('+result+')'); setContainer(stu.ID); setContainer(stu.Name); }, error: function () { setContainer('ERROR!'); } }); }
结果是这个样子的
上面代码向Handler.ashx发送一Post请求,比且带有参数{ID:’1’},可以看到结果,如果用调试工具可以发现,得到的result是一个json格式的字符串,也就是往Response写的对象序列化后的结果。这样就实现了比较专业些的方式调用Ajax,但是有一个问题依旧存在,HttpHandler会自动调用ProcessRequest方法,但是也只能调用该方法,如果想调用不同方法只能像普通页面那样传递一个参数表明调用哪个方法,或者写不同的Handler文件。
微软向来很贴心,看看微软怎么处理上面的困惑,那就是利用WebService,WebService配合SCriptManager有客户端调用的能力,在项目中添加一个Webservice文件
WebService.asmx
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace Web { ////// Summary description for WebService /// [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { [WebMethod] public Student GetStudent(int ID) { if (ID == 1) { return new Student() { ID = 1, Name = "Byron" }; } else { return new Student() { ID = 2, Name = "Frank" }; } }
[WebMethod] public string GetDateTime(bool isLong) { if (isLong) { return DateTime.Now.ToLongDateString(); } else { return DateTime.Now.ToShortDateString(); } } } }
代码中加黄的code默认是被注释掉的,要想让客户端调用需要把注释去掉,Service中定义了两个方法,写个测试方法让客户端调用第一个方法根据参数返回对应对象,首先需要在页面from内加上ScriptManager,引用刚才写的WebService文件
Default.aspx