ASP.NET using Ajax
The preliminary understanding of Ajax was introduced in the preliminary understanding of Ajax. This article will introduce how to use Ajax conveniently in ASP.NET. The first method is of course to use jQuery's ajax, which is powerful and easy to operate. The second method is to use .NET encapsulated ScriptManager.
$.ajax sends a get request to a normal page
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 A commonly used setting, all parameters and their explanations can be found in the jQuery official API document
1. type: request method get/post
2. url: requested Uri
3. async: whether the request is asynchronous
4 . headers: custom header parameters
5. data: parameters sent to the server
6. dataType: parameter format, common ones include string, json, xml, etc.
7. contents: one that determines how to parse the response. String/Regular Expression" map
8. contentType: 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 that is called after the request is successful10.error: the handle that is called after the request failsIf you haven’t used jQuery’s ajax, this seems a bit confusing, let’s take a look at a simple exampleFirst of all Use Visual Studio to create a new WebApplication, introduce jQuery.js into the project, and then add two pages. Default.aspx is used for testing. Default.aspx1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
这样向一个页面发送请求然后在Load事件处理程序中根据参数调用不同方法,清除Response,写入Response,终止Response,而且传入的参数局限性太大,好业余的赶脚,看看专业些解决方法。为project添加一个General Handler类型文件,关于HttpHandler相关内容本文不做详细解释,只需知道它可以非常轻量级的处理HTTP请求,不用走繁琐的页面生命周期处理各种非必需数据。
Handler.ashx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
|
关于这个类语法本文不做详细说明,每次发起HTTP请求ProcessRequest方法都会被调用到,Post类型请求参数和一再Request对象的Form中取得,每次根据参数ID值返回对应json对象字符串,为了展示json格式数据交互,需要为项目引入json.net这一开源类库处理对象序列化反序列化问题,然后创建一个Student类文件
Student.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
看看页面如何处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
结果是这个样子的
上面代码向Handler.ashx发送一Post请求,比且带有参数{ID:’1’},可以看到结果,如果用调试工具可以发现,得到的result是一个json格式的字符串,也就是往Response写的对象序列化后的结果。这样就实现了比较专业些的方式调用Ajax,但是有一个问题依旧存在,HttpHandler会自动调用ProcessRequest方法,但是也只能调用该方法,如果想调用不同方法只能像普通页面那样传递一个参数表明调用哪个方法,或者写不同的Handler文件。
WebService与ScriptManager
微软向来很贴心,看看微软怎么处理上面的困惑,那就是利用WebService,WebService配合SCriptManager有客户端调用的能力,在项目中添加一个Webservice文件
WebService.asmx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
|
代码中加黄的code默认是被注释掉的,要想让客户端调用需要把注释去掉,Service中定义了两个方法,写个测试方法让客户端调用第一个方法根据参数返回对应对象,首先需要在页面from内加上ScriptManager,引用刚才写的WebService文件
Default.aspx
1 2 3 4 5 6 7 8 9 10 11 |
|
然后添加JavaScript测试代码
1 2 3 4 5 6 7 8 |
|
测试代码中需要显示书写WebService定义方法完整路径,WebService命名空间.WebService类名.方法名,而出入的参数列表前几个是调用方法的参数列表,因为GetStudent只有一个参数,所以只写一个,如果有两个参数就顺序写两个,另外两个参数可以很明显看出来是响应成功/失败处理程序。看看执行结果:
观察仔细会发现使用ScriptManager和WebService组合有福利,在WebService中传回Student对象的时候并没有序列化成字符串,而是直接返回,看上面图发现对象已经自动转换为一json对象,result结果可以直接操作,果真非常贴心。而上一个例子中我们得到的response是一个json字符串,在客户端需要用eval使其转换为json对象。
ScriptManager+WebSefvice调用ajax带来了很大的便利性,但同时牺牲了很多灵活性,我们没法像jQuery那样指定很多设置有没有两全其美的办法呢
$.ajax+WebService
jQuery调用Handler几乎完美了,但是不能处理多个方法,上面例子我们可以发现WebService可以实现这一功能,那么能不能jQUery调用WebService的不同方法呢?答案是肯定的,试一试用jQuery调用刚才WebService定义的第二个方法。写一个测试函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
调用方式没有多大变化,简单依旧,只要把URL改为WebService路径+需要调用的方法名,然后把参数放到data里就可以了。我们看看结果:
As you can see from the picture above, jQuery will return an XML document by default when calling WebService, and the required data is in the
json.net and the sample source code of this article
json.net is an open source .net platform library for processing json. It can serialize complex objects such as Dictionay nesting. I will summarize its simple use when I have time. You can get its source code and official instructions from codeplex. The source code for this article can be obtained by clicking here.
For more articles related to ASP.NET using Ajax, please pay attention to the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The char array stores character sequences in C language and is declared as char array_name[size]. The access element is passed through the subscript operator, and the element ends with the null terminator '\0', which represents the end point of the string. The C language provides a variety of string manipulation functions, such as strlen(), strcpy(), strcat() and strcmp().

In C language, special characters are processed through escape sequences, such as: \n represents line breaks. \t means tab character. Use escape sequences or character constants to represent special characters, such as char c = '\n'. Note that the backslash needs to be escaped twice. Different platforms and compilers may have different escape sequences, please consult the documentation.

The usage methods of symbols in C language cover arithmetic, assignment, conditions, logic, bit operators, etc. Arithmetic operators are used for basic mathematical operations, assignment operators are used for assignment and addition, subtraction, multiplication and division assignment, condition operators are used for different operations according to conditions, logical operators are used for logical operations, bit operators are used for bit-level operations, and special constants are used to represent null pointers, end-of-file markers, and non-numeric values.

In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

In C language, char type conversion can be directly converted to another type by: casting: using casting characters. Automatic type conversion: When one type of data can accommodate another type of value, the compiler automatically converts it.

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

A strategy to avoid errors caused by default in C switch statements: use enums instead of constants, limiting the value of the case statement to a valid member of the enum. Use fallthrough in the last case statement to let the program continue to execute the following code. For switch statements without fallthrough, always add a default statement for error handling or provide default behavior.
