JSON is returned by a common ASP. NET handler or WebService.

Source: Internet
Author: User

Today, we will explain how to use a general handler or WebService in ASP. NET to return JSON to javascript.
Sample Code download: http://zsharedcode.googlecode.com/files/JQueryElementDemo.rar
The content in this article is as follows:
* Preparation
* General handler/ashx
* WebService/asmx
Preparation
If you want to return JSON through ashx or asmx, You need to reference the assembly System. web. extensions. dll, in.. NET 3.5 and 4.0 are already included by default. for. NET 2.0, 3.0, requires the installation of ASP. NET 2.0 AJAX, can be in http://www.microsoft.com/download/en/details.aspx? Displaylang = en & id = 883 download.
General handler/ashx
The general handler returns JSON. For different versions of. NET, see the following handler. ashx code:
<% @ WebHandler Language = "C #" Class = "handler" %>

Using System;
Using System. Web;
Using System. Web. Script. Serialization;
Using System. Collections. Generic;

Public class handler: IHttpHandler
{

Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "text/javascript ";
Context. Response. Cache. SetNoStore ();

String name = context. Request ["name"];

SortedDictionary <string, object> values = new SortedDictionary <string, object> ();
Values. Add ("message ",
String. IsNullOrEmpty (name )? "Anonymous ":
String. Format ("Hello {0}, {1}", name, DateTime. Now ));

Context. Response. Write (new JavaScriptSerializer (). Serialize (values ));
}

Public bool IsReusable
{
Get {return false ;}
}

}
In the above example, the object is converted to a JSON string through the Serialize method of the JavaScriptSerializer class. the converted object is SortedDictionary, which generates a string similar to {"message": "Hello x, 20xx-xx-xx xx: xx. if you want to return an array, you can define object [] for conversion. the context is also used in the code. response. cache. setNoStore (); to allow the browser to re-access each time it requests ashx, instead of using the cache.
If jQuery is used, you can use the following function to receive JSON:
Function (data ){
Alert (data. message );
}
WebService/asmx
In different versions. in. NET, accessing WebService through javascript and returning JSON is slightly different. first, you can use different Web. config file. all methods are listed. For more information, see:
. NET 2.0, 3.0 Web. config
<? Xml version = "1.0"?>
<Configuration>
<System. web>
<Compilation debug = "true">
<Assemblies>
<Add
Assembly = "System. Web. Extensions, Version = 1.0.61025.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35"/>
</Assemblies>
</Compilation>
<Pages/>
<HttpHandlers>
<Remove verb = "*" path = "*. asmx"/>
<Add verb = "*" path = "*. asmx"
Type = "System. Web. Script. Services. ScriptHandlerFactory"
Validate = "false"/>
</HttpHandlers>
</System. web>
</Configuration>
. NET 3.5 Web. config
. NET 4.0 Web. config
The preceding two versions of Web. config can be viewed in Web.3.5.config and Web.4.config in the sample package.
The following is the code for webservice. asmx/webservice. cs:
<% @ WebService Language = "C #" CodeBehind = "~ /App_Code/webservice. cs "Class =" webservice "%>
Using System;
Using System. Web;
Using System. Web. Services;
Using System. Web. Services. Protocols;
Using System. Web. Script. Services;
Using System. Web. Script. Serialization;
Using System. Collections. Generic;

[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = WsiProfiles. BasicProfile1_1)]
[ScriptService]
Public class webservice: System. Web. Services. WebService
{

[WebMethod]
[ScriptMethod]
Public SortedDictionary <string, object> Save (string name)
{
This. Context. Response. Cache. SetNoStore ();

SortedDictionary <string, object> values = new SortedDictionary <string, object> ();
Values. Add ("message ",
String. IsNullOrEmpty (name )? "Anonymous ":
String. Format ("Hello {0}, {1}", name, DateTime. Now ));

Return values;
}

}
Add a property ScriptService for the class and use the property ScriptMethod for the methods in the class. This allows javascript to call these methods. here, you do not need to use JavaScriptSerializer to convert the object to a JSON string, but directly return the object. the above code returns SortedDictionary, in. NET 2.0, 3.0 will be similar to the form of {"message": "Hello x, 20xx-xx-xx xx: xx"}, and. NET 3.5, 4.0 is {"d": {"message": "Hello x, 20xx-xx-xx xx: xx "}}, therefore, the following functions can be used in jQuery to accept JSON:
Function (data ){
Alert (data. message );
}

Function (data ){
Alert (data. d. message );
}
JQueryElement is an open-source shared code that can be downloaded on the http://code.google.com/p/zsharedcode/wiki/Download page dll or source code.
Actual process Demonstration: http://www.tudou.com/programs/view/rHCYHX9cmcI/, it is recommended to watch in full screen.
Welcome to panzer open source project, http://zsharedcode.googlecode.com/, which contains IEBrowser control WebBrowser to execute various js and jQuery scripts as well as recording functions and jQueryUI Asp.net controls JQueryElement, Weibo: http://t.qq.com/zoyobar

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.