ASP. NET Using Ajax), asp.net using ajax

Source: Internet
Author: User

ASP. NET uses Ajax (for conversion), and asp.net uses ajax

The previous preliminary understanding of Ajax introduces the preliminary understanding of Ajax, this article will introduce in ASP. NET, the first is to use jQuery Ajax, Which is powerful and easy to operate, and the second is to use.. NET encapsulated ScriptManager.

$. Ajax sends a get request to a common page

This is the simplest method. First, you can understand the jQuery ajax syntax. The most common call method is as follows: $. ajax ({settings}); several common setting parameters can be found in the official jQuery API documentation.

1. type: Request Method get/post

2. url: the 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 parameters include string, json, and xml.

7. contents: Determine how to parse a "String/regular expression" map of response

8. contentType: The content encoding type of the amount of data sent to the server, which defaults to "application/x-www-form-urlencoded; charset = UTF-8 "".

9. success: handle called after successful request

10. error: handle called after request failure

I have never used jQuery's ajax. In this case, I think it's a bit confusing. Let's look at a simple example.

First, use Visual Studio to create a WebApplication, introduce jQuery. js into the project, and then add two pages, Default. aspx for testing.

Default. aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Web.Default" %><!DOCTYPE html >

As the request page, NormalPage. aspx is not processed. In Default. in JavaScript on the aspx page, we can see that the testGet function uses jQuery's ajax to convert to Normal. aspx sends a get request. parameters that are not written use the default jQuery parameter. This call does not use any parameter, which is simple to Normal. the aspx page sends a request. If the request is successful, alert will all respond (that is, the success method parameter: result, jQuery will pass responseText to the first parameter of the success method ), if the request fails, add an error message text to the DIV. If everything is Normal, you can see the dialog box that appears. The content in the dialog box is the content of the Normal. aspx page.

A simple get request is completed, and such a result is generally not very useful, nor is it the intention of ajax. Ajax is mainly used to send a specific request to the server asynchronously using JavaScript, obtain server-related data, such as querying the server about the weather, obtaining weather data, and updating the page, instead of obtaining the whole page. In other words, ajax is used to update page data without updating the entire page. The server only needs to provide us with data, which requires calling specific methods on the server side.

$. Ajax GET requests call server-specific methods

At this time, we need to modify NormalPage. aspx and add several methods for it for the 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 (); // Clear all previously generated Response content if (! String. isNullOrEmpty (action) {switch (action) {case "getTime": Response. write (GetTime (); break; case "getDate": Response. write (GetDate (); break;} Response. end (); // stop the subsequent write action of Response to ensure that only the content we write in Response} private string GetDate () {return DateTime. now. toShortDateString ();} private string GetTime () {return DateTime. now. tow.timestring ();}}}

Then add a new method for Default. aspx and modify the onclick method of the button as a 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 makes some modifications based on the testGet function. First, the success method is changed, and the response is written to the page. Then, the data parameter is added to the request, the request sends a key-value pair of action: getTime to the server. In the get request, jQuery converts this parameter to a url parameter, which works the same way as this method.

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

Check the execution result. This is the result of Chrome monitoring.

If debugging finds that this request calls the Server Page NormalPage. aspx's GETime method, and response only contains useful data. If you change the value of the parameter in the request to getDate, the corresponding GetDate method will be called.

$. Ajax POST and json

In this way, a request is sent to a page and then different methods are called in the Load event handler according to the parameters. The Response is cleared, the Response is written, and the Response is terminated. The limitations of the input parameters are too large, take a look at some professional solutions. Add a General Handler type file for the project. This article does not explain HttpHandler-related content in detail. You only need to know that it can handle HTTP requests very lightweight, you do not need to process all kinds of non-essential data in the tedious page lifecycle.

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;            }        }    }}

This section does not describe this syntax in detail. Each time an HTTP Request is initiated, the ProcessRequest method is called, and the Post type Request parameters are obtained from the Form of the Request object, each time the corresponding json object string is returned Based on the parameter ID value, in order to display json format data interaction, the json.net open source class library needs to be introduced for the project to handle Object serialization deserialization issues, and then a Student class file is created.

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; }    }}

How to handle the page

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!');                }            });        }

The result is like this.

The above code is directed to Handler. ashx sends a Post request with the {ID: '1'} parameter. The result is displayed. If you use a debugging tool, the result is a json string, that is, the serialized result of the object written to Response. In this way, Ajax is called in a more professional way, but there is still a problem. HttpHandler will automatically call the ProcessRequest method, but it can only call this method, if you want to call different methods, you can only pass a parameter like a normal page to indicate which method to call or write different Handler files.

WebService and ScriptManager

Microsoft has always been very considerate. Let's take a look at how Microsoft handles the above confusions, that is, using WebService and WebService with SCriptManager to have the ability to call the client and add a Webservice file to the project.

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. tow.datestring ();
}
}

    }}

The code that is yellow in the code is commented out by default. To call the client, you need to remove the comment. The Service defines two methods, write a test method to allow the client to call the first method to return the corresponding object according to the parameter. First, add ScriptManager to the page from to reference the WebService file just written.

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

Then add the JavaScript test code

function testPost2() {            Web.WebService.GetStudent(1, function (result) {                setContainer(result.ID);                setContainer(result.Name);            }, function () {                setContainer('ERROR!');            });        }

The test code must show the complete path of the WebService definition method, WebService namespace. webService class name. method Name, while the first few parameters in and out of the list are the list of parameters that call the method, because GetStudent only has one parameter, so write only one. If there are two parameters, write them in sequence, the other two parameters clearly show that the response is successful/failed. Check the execution result:

After careful observation, we will find that the combination of ScriptManager and WebService has benefits. When the Student object is returned in WebService, It is not serialized as a string, but directly returned, as shown in the figure above, the object has been automatically converted to a json object, and the result can be directly operated. It is very considerate. In the previous example, the response is a json string, which needs to be converted to a json object using eval on the client.

ScriptManager + WebSefvice it brings great convenience to call ajax, but at the same time it sacrifices a lot of flexibility. We can't specify many settings like jQuery. Is there a perfect solution?

$. Ajax + WebService

JQuery calls Handler almost perfectly, but it cannot process multiple methods. The preceding example shows that WebService can implement this function. Can jQUery call different WebService methods? The answer is yes. Try jQuery to call the second method defined by WebService just now. Write a test function

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

The call method remains simple. You only need to change the URL to the WebService path + method name to be called, and then put the parameter in data. Let's look at the results:

As you can see, jQuery calls WebService and returns an XML document by default. In the <string> node, you only need to use jQuery to parse the xml syntax to get the data easily. What if I want to return a json object? Then we need to use json.net for serialization like calling Handler, and then use eval for conversion at the front end, which is not too complicated. This mode is the most frequently used in projects. This ensures jQuery's flexibility and allows you to write multiple methods in a Service for calling, without having to go through complex page lifecycles.

Json.net and sample source code in this article

Json.net is an open source. the net platform can serialize complex objects such as Dictionay nesting when processing json databases. For more information about its simple use, we will summarize it. You can get its source code and official instructions from codeplex. You can click here to obtain the source code of this article.


How does aspnet make AJAX not jump after submitting a form?

Ajax cannot use form for action.

Try to use an xmlhttp object to get An aspx program directly.
The aspx program can return the result to an xml string. js can parse the result and place the result on the page.

If (window. ActiveXObject)
{
XmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ");
}
Else if (window. XMLHttpRequest)
{
XmlHttp = new XMLHttpRequest ();
}

Try
{
XmlHttp. onreadystatechange = handleStateChange;
XmlHttp. open ("GET", "checkuser. aspx? Uname = abc & pwd = 123 ", false );
XmlHttp. setRequestHeader ("If-Modified-Since", "0 ");
XmlHttp. send (null );
If (xmlHttp. status = 200 | xmlHttp. status = 0)
{
Htmlstr = xmlHttp. responseText;
// Parse this string to find out the Success Failure in xml.
Alert (htmlstr); // htmlstr can be obtained here
}

}
Catch (exception)
{
Alert ("The resource you want to access does not exist! ");
}

How does aspnet use ajax?

Asp.net generally uses jquery. js implements ajax. the backend of ajax requests can be. the aspx page can also be. the ashx page is usually used. ashx (general applications) can be sent to you If jquery is needed.

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.