ASP. NET uses Ajax

Source: Internet
Author: User
Tags net serialization object serialization
Prior to the initial understanding of Ajax introduced the initial understanding of Ajax, This article will show you how to use Ajax in ASP. The first is, of course, Ajax with jquery, powerful and easy to operate, and the second is using. NET packaged ScriptManager.

$.ajax send a GET request to a normal page

This is the simplest way, the first simple understanding of the jquery Ajax syntax, the most common way to call: $.ajax ({settings}); There are several commonly used setting, all parameters and their explanations can go to jquery official API document query

1. Type: Request Mode Get/post

2. URL: The requested URI

3. Async: Whether the request is asynchronous

4. Headers: Custom Header Parameters

5. Data: Parameters destined for the server

6. DataType: Parameter format, common with string, JSON, XML, etc.

7. Contents: Decide 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, its default value is "application/x-www-form-urlencoded; Charset=utf-8 "".

9. Success: Handle to call after successful request

10.error: Handle called after a request fails

Ajax without jquery so look at some foggy feeling and see a simple example

First use Visual Studio to create a new WebApplication, bring jquery.js into Project, and add two pages, default.aspx as a test

Default.aspx

<%@ page language= "C #" autoeventwireup= "true" codebehind= "Default.aspx.cs" inherits= "Web.default"%><! DOCTYPE HTML >

Normalpage.aspx as a request page, do not do any processing first. In JavaScript on the Default.aspx page, you can see that the Testget function uses jquery's Ajax to send a GET request to normal.aspx, which uses the jquery default parameter, which does not use any parameters, simply to normal.as PX page send request, the request is successful then alert all response (that is, the success method parameter: Result,jquery will responsetext into the success method the first parameter), the request fails to add a line of error text to the Div. If everything is OK, you can see the page Popup dialog box, the contents of the dialog box is normal.aspx page content

A simple GET request is done, the result is generally not much use, and is not the Ajax intent, using AJAX mainly to use JavaScript can asynchronously send a specific request to the server, to obtain server-related data, such as to the server to inquire about the weather, and then get weather data, Update 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 need the server to give us data, which need to call the server-side specific methods.

$.ajax GET request Call Server-specific method

We need to modify normalpage.aspx at this time to add several methods 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 Voi            d Page_Load (object sender, EventArgs e) {string action = request.querystring["Action"]; Response.Clear (); Clears 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 response subsequent write actions to ensure that only we write the content in response} private string GetDate () {return DateTime.Now.To        Shortdatestring (); private String GetTime () {return DateTime.Now.toshorttimestring (); }    }}

Then add a new method for 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 a slight modification on the basis of the Testget function, first making a change to the success method, writing the resulting response to the page, and then adding the data parameter to the request, requesting a Action:gettime key-value pair to be sent to the server. , jquery will turn this parameter into a URL parameter in a GET request, which is the same as the writing effect

function TestGet3 () {            $.ajax ({                type: ' Get ',                URL: ' normalpage.aspx? Action=gettime ',                async:true,                success:function (result) {                    Setcontainer (result);                },                error: function () {                    setcontainer (' error! ');                }            });        }

Take a look at the effect, this is Chrome's monitoring results

If you debug the server page normalpage.aspx that we found this request to call the Getime method, and response contains only the useful data, if the parameter in the request is changed to getdate, then the corresponding getdate method is called.

$.ajax Post and JSON

This sends a request to a page and then calls the different methods in the Load event handler according to the parameters, clears the response, writes the response, terminates the response, and the passed parameter limitation is too big, the good amateur bright, looks at the specialized solution method. Add a general handler type file for project, about HttpHandler related content This article does not explain in detail, just know that it can handle HTTP requests very lightweight, without having to go through the tedious page life cycle to process various non-essential data.

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 article does not elaborate on this type of syntax, each time the HTTP request ProcessRequest method is called, the Post type request parameter and the repeated request object's form are taken, each time the corresponding JSON object string is returned according to the parameter ID value, To demonstrate JSON-formatted data interaction, you need to introduce json.net, an open source class library for the project, to handle the object serialization deserialization problem, and then create a student class file

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

See how the page is handled

function Testpost () {            $.ajax ({                type: ' Post ',                URL: ' handler.ashx ',                async:true,                data: {ID: ' 1 '},< C5/>success:function (Result) {                    Setcontainer (result);                    var stu =eval (' (' +result+ ') ');                    Setcontainer (stu.id);                    Setcontainer (Stu. Name);                },                error:function () {                    setcontainer (' error! ');}}            );        

It turned out this way.

The above code sends a POST request to handler.ashx, and with the parameter {ID: ' 1 '}, you can see the result, and if you can find it with the Debug tool, the resulting result is a JSON-formatted string, that is, the results of serializing the object to response. This enables a more professional way to call Ajax, but there is a problem still exists, HttpHandler will automatically call the ProcessRequest method, but can only call the method, if you want to call different methods can only pass a parameter like a normal page to indicate which method to invoke, or write a different handler file.

WebService and ScriptManager

Microsoft has always been very sweet, to see how Microsoft handles the confusion above, that is, the ability to use Webservice,webservice with ScriptManager to have client calls, 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 (Nam Espace = "http://tempuri.org/")] [webservicebinding (ConformsTo = wsiprofiles.basicprofile1_1)] [System.componentmode L.toolboxitem (FALSE)]//To allow this Web Service to is called from script, using ASP. Uncomment the Followin     G Line. [System.Web.Script.Services.ScriptService] public class WebService:System.Web.Services.WebService {[Webmet HOD] public Student getstudent (int id) {if (id = = 1) {return new Stu            Dent () {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 (); }            }    }}

The code is yellow by default is commented out, in order to let the client call to remove the comment, the service defines two methods, write a test method for the client to call the first method to return the corresponding object according to the parameters, first need to add ScriptManager in the page from, Reference the WebService file that you just wrote

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 full path of the Write WebService definition method needs to be displayed in the test code. WebService namespace. WebService class name. The name of the method, and the first few arguments in the list are the parameter list of the calling method, because Getstudent has only one argument, so write only one, if there are two parameters in order to write two, the other two parameters can be clearly seen to be a successful response /Failure handler. Take a look at the results:

Watch carefully will find the use of ScriptManager and webservice combination of benefits, in WebService back to the student object is not serialized into a string, but directly return, see the above figure found that the object has been automatically converted to a JSON object, Result results can be directly manipulated, indeed very intimate. The response we get in the previous example is a JSON string that the client needs to use Eval to convert to a JSON object.

Scriptmanager+websefvice calls Ajax for great convenience, but at the same time sacrificing a lot of flexibility, we can't specify many settings like jquery.

$.ajax+webservice

jquery calls handler almost perfect, but can not handle multiple methods, the above example we can find WebService can achieve this function, then can jquery call WebService different methods? The answer is yes, try jquery to invoke 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 mode does not change much, simply still, as long as the URL is changed to WebService Path + need to call the method name, and then put the parameters in the data can be. Let's look at the results:

As you can see, the jquery call WebService returns an XML document by default, and the data needed in the <string> node can be easily obtained by using jquery to parse the XML syntax. What if you want to return a JSON object? You'll have to use json.net serialization just like calling Handler, and then the front end uses the eval transform, and it's not too complicated. I use this pattern most often in my project, which preserves the flexibility of jquery and can write multiple methods for invocation in one service without having to go through the complex page life cycle

Json.NET and sample source code for this article

Json.NET is an open source. NET platform that handles JSON libraries, can serialize complex objects such as Dictionay nesting, and has time to summarize its simple use, and can get its source code and official instructions from CodePlex. The source code of this article can be obtained by clicking here.


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.