Asp.net WebService return JSON operation method

Source: Internet
Author: User

See the following handler. ashx code:

The code is as follows: Copy 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:

The code is as follows: Copy code

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

The code is as follows: Copy code

<? 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:

The code is as follows: Copy code

<% @ 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:

The code is as follows: Copy code

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

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.