ASP.NET using Ajax

高洛峰
Release: 2016-12-16 16:02:31
Original
1685 people have browsed it

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 successful

10.error: the handle that is called after the request fails

If you haven’t used jQuery’s ajax, this seems a bit confusing, let’s take a look at a simple example

First 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.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Web.Default" %>
<!DOCTYPE html >
<html>
<head runat="server">
    <title>Ajax</title>
    <script src="jQuery.js" type="text/javascript"></script>
    <style type="text/css">
        html, body, form
        {
            width: 100%;
            height: 100%;
            padding: 0px;
            margin: 0px;
        }
        
        #container
        {
            margin: 100px;
            height: 300px;
            width: 500px;
            background-color: #eee;
            border: dached 1px #0e0;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div id="container">
        <input type="button" value="Test Ajax" onclick="testGet()" />
        <br />
    </div>
    <script type="text/javascript">
        function setContainer(text) {
            document.getElementById("container").innerHTML += (&#39;<br/>&#39; + text);
        }

        function testGet() {
            $.ajax({
                type: &#39;get&#39;,
                url: &#39;NormalPage.aspx&#39;,
                async: true,
                success: function (result) {
                    alert(result);
                },
                error: function () {
                    setContainer(&#39;ERROR!&#39;);
                }
            });
        }
    </script>
    </form>
</body>
</html>
Copy after login

NormalPage.aspx is used as the request page. No processing is done in Default. In the JavaScript in the aspx page, you can see that the testGet function uses jQuery's ajax to send a get request to Normal.aspx. The unwritten parameters use jQuery default parameters. This call does not use any parameters and simply sends it to the Normal.aspx page. Request, if the request is successful, all responses will be alerted (that is, the success method parameter: result, jQuery will pass the responseText into the first parameter of the success method), if the request fails, a line of error text will be added to the DIV. If everything is normal, you can see the page. A dialog box pops up, and the content in the dialog box is the content of the Normal.aspx page

ASP.NET 使用Ajax

A simple get request is completed. Such a result is generally not very useful, and it is not the intention of ajax. You can use Ajax mainly if you want to use JavaScript. Asynchronously send a specific request to the server to obtain server-related data, such as asking the server for the weather, then getting the weather data, updating the page instead of getting the entire page. In other words, using Ajax itself is to get rid of updating the entire page to update the page data. This mode only requires the server to give us data, which requires calling specific methods on the server side.

$.ajax GET request calls server-specific method

We need to modify NormalPage.aspx at this time, 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();
        }
    }
}
Copy after login

Then add a new method to Default.aspx, and modify it The onclick method of button is a newly written function

function testGet2() {
            $.ajax({
                type: &#39;get&#39;,
                url: &#39;NormalPage.aspx&#39;,
                async: true,
                data:{action:&#39;getTime&#39;},
                success: function (result) {
                    setContainer(result);
                },
                error: function () {
                    setContainer(&#39;ERROR!&#39;);
                }
            });
        }
Copy after login

The testGet2 function is slightly modified based on the testGet function. First, the success method is changed and the obtained response is written to the page; then the data parameter is added to the request. The request sends an action: getTime key-value pair to the server. In the get request, jQuery will convert this parameter into a url parameter. The above writing method has the same effect as this one

function testGet3() {
            $.ajax({
                type: &#39;get&#39;,
                url: &#39;NormalPage.aspx?action=getTime&#39;,
                async: true,
                success: function (result) {
                    setContainer(result);
                },
                error: function () {
                    setContainer(&#39;ERROR!&#39;);
                }
            });
        }
Copy after login

Look at the execution effect, this is Chrome's monitoring Result

ASP.NET 使用Ajax

If we find that this request calls the GETime method of the server page NormalPage.aspx, and the response only contains useful data, if the value of the parameter in the request is changed to getDate, then the corresponding GetDate will be called method.

$.ajax POST with json

这样向一个页面发送请求然后在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>
    /// Summary description for Handler
    /// </summary>
    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;
            }
        }
    }
}
Copy after login

关于这个类语法本文不做详细说明,每次发起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; }
    }
}
Copy after login

看看页面如何处理

function testPost() {
            $.ajax({
                type: &#39;post&#39;,
                url: &#39;Handler.ashx&#39;,
                async: true,
                data: { ID: &#39;1&#39; },
                success: function (result) {
                    setContainer(result);
                    var stu =eval (&#39;(&#39;+result+&#39;)&#39;);
                    setContainer(stu.ID);
                    setContainer(stu.Name);
                },
                error: function () {
                    setContainer(&#39;ERROR!&#39;);
                }
            });
        }
Copy after login

结果是这个样子的

ASP.NET 使用Ajax

上面代码向Handler.ashx发送一Post请求,比且带有参数{ID:’1’},可以看到结果,如果用调试工具可以发现,得到的result是一个json格式的字符串,也就是往Response写的对象序列化后的结果。这样就实现了比较专业些的方式调用Ajax,但是有一个问题依旧存在,HttpHandler会自动调用ProcessRequest方法,但是也只能调用该方法,如果想调用不同方法只能像普通页面那样传递一个参数表明调用哪个方法,或者写不同的Handler文件。

WebService与ScriptManager

微软向来很贴心,看看微软怎么处理上面的困惑,那就是利用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>
    /// Summary description for WebService
    /// </summary>
    [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();

    
            }

    
        }
    }
}
Copy after login

代码中加黄的code默认是被注释掉的,要想让客户端调用需要把注释去掉,Service中定义了两个方法,写个测试方法让客户端调用第一个方法根据参数返回对应对象,首先需要在页面from内加上ScriptManager,引用刚才写的WebService文件

Default.aspx

<form id="form1" runat="server">
    <asp:ScriptManager ID="clientService" runat="server">
        <Services>
            <asp:ServiceReference Path="~/WebService.asmx" />
        </Services>
    </asp:ScriptManager>
    <div id="container">
        <input type="button" value="Test Ajax" onclick="testPost2()" />
        <br />
    </div>
...
Copy after login

然后添加JavaScript测试代码

function testPost2() {
            Web.WebService.GetStudent(1, function (result) {
                setContainer(result.ID);
                setContainer(result.Name);
            }, function () {
                setContainer(&#39;ERROR!&#39;);
            });
        }
Copy after login

测试代码中需要显示书写WebService定义方法完整路径,WebService命名空间.WebService类名.方法名,而出入的参数列表前几个是调用方法的参数列表,因为GetStudent只有一个参数,所以只写一个,如果有两个参数就顺序写两个,另外两个参数可以很明显看出来是响应成功/失败处理程序。看看执行结果:

ASP.NET 使用Ajax

观察仔细会发现使用ScriptManager和WebService组合有福利,在WebService中传回Student对象的时候并没有序列化成字符串,而是直接返回,看上面图发现对象已经自动转换为一json对象,result结果可以直接操作,果真非常贴心。而上一个例子中我们得到的response是一个json字符串,在客户端需要用eval使其转换为json对象。

ScriptManager+WebSefvice调用ajax带来了很大的便利性,但同时牺牲了很多灵活性,我们没法像jQuery那样指定很多设置有没有两全其美的办法呢

$.ajax+WebService

jQuery调用Handler几乎完美了,但是不能处理多个方法,上面例子我们可以发现WebService可以实现这一功能,那么能不能jQUery调用WebService的不同方法呢?答案是肯定的,试一试用jQuery调用刚才WebService定义的第二个方法。写一个测试函数

function testPost3() {
            $.ajax({
                type: &#39;post&#39;,
                url: &#39;WebService.asmx/GetDateTime&#39;,
                async: true,
                data: { isLong: true },
                success: function (result) {
                    setContainer($(result).find(&#39;string&#39;).text());
                },
                error: function () {
                    setContainer(&#39;ERROR!&#39;);
                }
            });
        }
Copy after login

调用方式没有多大变化,简单依旧,只要把URL改为WebService路径+需要调用的方法名,然后把参数放到data里就可以了。我们看看结果:

ASP.NET 使用Ajax

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 node. You only need to use jQuery to parse the xml syntax to easily get the data. What if you want to return a json object? Then you have to use json.net serialization just like calling Handler, and then use eval to convert it on the front end, which won't be too complicated. I use this mode most often in projects, which not only maintains the flexibility of jQuery, but also allows me to write multiple methods in a Service for calling without having to go through the complicated page life cycle

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!