Use asp.net generic handler or WebService to return JSON implementation code _ Practical Tips

Source: Internet
Author: User
Tags datetime serialization

Sample code Download: Http://zsharedcode.googlecode.com/files/JQueryElementDemo.rar

The content contained in this article is as follows:

* Prepare
* General processing program/ASHX
* Webservice/asmx Preparation

If you want to return JSON via ashx or ASMX, you need to reference the assembly System.Web.Extensions.dll, which is already included by default in. NET 3.5, 4.0. For. NET 2.0, 3.0, you need to install ASP.net 2.0 AJAX, which can be used in http://www.microsoft.com/download/en/details.aspx?displaylang=en&id= 883 download.

General Handler/ashx

Using a generic handler to return JSON, for different versions of. NET, see the following HANDLER.ASHX code:

Copy Code code as follows:

<%@ 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)? "John Doe":
String. Format ("Hello {0}, {1}", name, DateTime.Now));
Context. Response.Write (New JavaScriptSerializer (). Serialize (values));
}
public bool IsReusable
{
get {return false;}
}
}

In the example above, the object is converted to a string of JSON by the Serialize method of the JavaScriptSerializer class. The transformed object is SortedDictionary, which generates {"Message": "Hello X, 20xx-xx-xx xx:xx:xx"} Similar strings. If you need to return an array, you can define object[] to convert. The context is also used in the code. Response.Cache.SetNoStore (); To have the browser reconnect every time the ashx is requested, rather than using the cache.
If you use JQuery, you can use the following function to receive JSON:
Copy Code code as follows:

function (data) {
alert (data.message);
}

Webservice/asmx
In different versions of. NET, it is slightly different to access WebService and return JSON via JavaScript. First of all, you can use different web.config files. The law is listed, if necessary please refer to:
. NET 2.0, 3.0 web.config
Copy Code code as follows:

<?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/>
<remove verb= "*" path= "*.asmx"/>
<add verb= "*" Path= "*.asmx"
Type= "System.Web.Script.Services.ScriptHandlerFactory"
Validate= "false"/>
</system.web>
</configuration>

. NET 3.5 Web.config
. NET 4.0 Web.config
The above two versions of Web.config can be viewed in web.3.5.config and web.4.config in the sample compression pack.
Here is the code for Webservice.asmx/webservice.cs:
Copy Code code as follows:

<%@ 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)? "John Doe":
String. Format ("Hello {0}, {1}", name, DateTime.Now));
return values;
}
}

Add property ScriptService to the class and use property Scriptmethod on the methods in the class to have JavaScript invoke these methods. Instead of using JavaScriptSerializer to convert an object to a JSON string, you can return the object directly. The above code returns SORTEDDICTIONARY, in. NET 2.0, 3.0 will resemble {"message": "Hello X, 20xx-xx-xx xx:xx:xx"}, and for. NET 3.5, 4.0 is {" D ": {" message ":" Hello X, 20xx-xx-xx xx:xx:xx "}}, so you can use the following function in JQuery to accept JSON, respectively:
Copy Code code as follows:

function (data) {
alert (data.message);
}
function (data) {
alert (data.d.message);
}

jqueryelement is an Open-source shared code that can be downloaded from a DLL or source code on a http://code.google.com/p/zsharedcode/wiki/Download page.

actual Process Demo: http://www.tudou.com/programs/view/rHCYHX9cmcI/, recommended Full-screen viewing.

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.