jquery calls a WCF service to pass a JSON object

Source: Internet
Author: User

The following example uses WCF to create a service port that can be accessed by an ASP. NET page via jquery's AJAX approach, and we will use AJAX technology at the client to communicate with the WCF service. Instead of using the ASP. NET AJAX Library, we use jquery only to connect to the Web Service, and that's why we're not using the AJAX library because we've already used jquery in our project, and it's already able to handle all of the Ajax requests and all the functionality, and If we use the ASP. NET AJAX Library, we also have to include more than 80Kb of data (debug mode will be larger), but this is not to say that the ASP is not practical, in fact, if you use the same class library, we can write a lot less extra code, But this example is to illustrate how we invoke Web services without a good client agent.

WCF Services:

Let's create a website and then add a ajax-enabled WCFservice to create the WCF services. (Make sure you're using the correct. Net Framework version, I'm using 3.5)

After we add the service, it will automatically enter the service's post code file, go ahead and browse around the file for a second.

The first thing we need to do is find "aspnetcompatibilityrequirements" and set its value to "allowed":

[Aspnetcompatibilityrequirements (Requirementsmode = aspnetcompatibilityrequirementsmode.allowed)]

This property is set to run our service in ASP. NET compatibility mode, and if we do not set this value to "allowed", then we cannot access the service through ASP. This property is when you add " ajax-enabled WCF Service "When it is automatically generated. See MSDN for more details.

Now look at the automatically generated post code file, we can find that there is a "operationcontract" feature labeled "DoWork()" method, this method is generated automatically, We will use this method to complete the following example. Let's add a "webget" attribute to the method, and set the value of "Requestformat" to "Json." We'll come back to this method with another feature Requestformat, WebGet, like the get verb, acts on a uritemplate (this is not discussed further), and the Requestformat feature allows us to receive requests in JSON format.

Our "DoWork()" method is as follows:

[OperationContract]
[WebGet (Requestformat=webmessageformat.json)]
public void DoWork ()
{
ADD your operation implementation here
Return
}

Model of the object:

We want to pass an object called "person" through "DoWork()", which first creates a person object written to the header of the current class, which contains fields and properties (Name, age, and the types of Shoes They own), this class also acts as the structure of the JSON being passed.

[Serializable]
[DataContract (Namespace = "http://www.dennydotnet.com/", Name = "person")]
public class Person
{
private string _name = String. Empty;
private int _age = 0;

[DataMember (isrequired = true, name = "name")]
public string Name
{
get {return _name;}
set {_name = value;}
}

[DataMember (IsRequired = true, Name = "age")]
public int Age
{
get {return _age;}
set {_age = value;}
}

[DataMember (IsRequired = true, Name = "Shoes")]
Public list<string> Shoes;
}

We have already labeledthe name and namespace of the "person" class with a contract, and we still need to grant the attribute to the data member attribute, set "IsRequired" for each property and specify its name. You only need to specify the name, if it is not the same as the property name. For example, if you have a property called "level", but you assign a value of "Rank" to the data member attribute, now we have to go back and modify our "DoWork()" method to receive the person object as a parameter. Specify the following code block.

[OperationContract]
[WebGet (Requestformat=webmessageformat.json)]
public void DoWork (person p)
{
ADD your operation implementation here
Return
}

to configure the Web. config file:
We only need to make minor changes to the Web. config file to access the service. First, join a servicebehavior to allow HTTP GET requests, and then add some debugging options to help. The code is as follows:

Below </endpointBehaviors>

<serviceBehaviors>
<behavior name= "Serviceaspnetajaxbehavior" >
<servicemetadata httpgetenabled= "true" httpgeturl= ""/>
<servicedebug httphelppageenabled= "true" includeexceptiondetailinfaults= "true"/>
</behavior>
</serviceBehaviors>

In <services> here </services> between, your code is as follows:

<service name= "service" behaviorconfiguration= "Serviceaspnetajaxbehavior" >
<endpoint address= "" behaviorconfiguration= "Serviceaspnetajaxbehavior"
binding= "WebHttpBinding" contract= "Service"/>
<endpoint address= "Mex" binding= "mexHttpBinding" contract= "IMetadataExchange"/>
</service>

A Security Note about the following line:

<servicedebug httphelppageenabled= "true" includeexceptiondetailinfaults= "true"/>

Allowing exception details can expose internal application information including personally identifiable or otherwise Sens Itive information. Setting the option to True was only recommended as a a-to temporarily debug your service!!

Your Web. config file is modified as follows:

Back to front page:
Now that our service has been created and configured, focus on the Front page section (make sure the page has referenced the Jquery.js file), first create a simple JSON object to pass to the service, and we create the JSON object on the basis of the person class structure.

var = {"Name": "Denny", "Age": MyData, "Shoes": ["Nike", "Osiris", "Etnies"]};

If you are not familiar with JSON, we can think of it as an object, and this gadget will help you to see (jsonviewer):

We need to use WCF and jquery for Ajax communication, the following code creates an Ajax call, sets the Get method on the head, and the content type is Application/json, the path of the URL to the Svc file of the WCF service, and then adds/ and the name of the method to be executed, where we are going to invoke the DoWork () method, data is used to pass the parameters, in order for jquery not to automatically process our data, set ProcessData to False, we also added the handling of success and error, Learn more about the process after Ajax finishes.

function Sendajax (data) {
$.ajax ({
Type: "GET",
ContentType: "Application/json",
URL: "Service.svc/dowork",
Data:data,
Processdata:false,
Success:function (msg) {
Alert ("Data saved!");
},
Error:function (XMLHttpRequest, Textstatus, Errorthrown) {
Alert ("Error occured!");
}
});
}

Unfortunately, there's a small problem here, and we have to send a real JSON string as a parameter pass. But there's no easy way to convert a JSON object to a string, and if you try Data.tostring (), you get an "[Object]" value. That's not what we want.
So here we're going to modify the method so that it can convert the JSON into a string.

note* The JSON de/serialization handles date/time in a specific. The json2string function below does not take this to account. I ' m sure there is some implementations out there which would work with ASP. For more information on this you can go to here.

Update [4/11/08]: The javascript below have a few issues so it's been suggested that's should use the json.org version to "Stringify" your Object. You can download the script from here.

Update [4/25/08]: Rick Strahl have modified the json.org script so that it would properly create the dates to work with ASP. NET AJAX (read his Post

function json2string (strobject) {
var c, I, l, s = ', V, p;

Switch (typeof strobject) {
Case ' object ':
if (strobject) {
if (strobject.length && typeof strobject.length = = ' number ') {
for (i = 0; i < strobject.length; ++i) {
v = json2string (strobject[i]);
if (s) {
s + = ', ';
}
s + = V;
}
Return ' [' + S + '] ';
} else if (typeof strobject.tostring! = ' undefined ') {
For (i in Strobject) {
v = strobject[i];
if (typeof v! = ' undefined ' && typeof v! = ' function ') {
v = json2string (v);
if (s) {
s + = ', ';
}
s + = json2string (i) + ': ' + V;
}
}
Return ' {' + S + '} ';
}
}
return ' null ';
Case ' number ':
return Isfinite (strobject)? String (strobject): ' null ';
Case ' string ':
L = strobject.length;
s = ' ";
for (i = 0; i < L + = 1) {
c = Strobject.charat (i);
if (c >= ") {
if (c = = '//' | | c = = ' "') {
s + = '//';
}
s + = C;
} else {
Switch (c) {
Case '/b ':
s + = '//b ';
Break
Case '/F ':
s + = '//f ';
Break
Case '/n ':
s + = '//n ';
Break
Case '/R ':
s + = '//r ';
Break
Case '/t ':
s + = '//t ';
Break
Default
c = C.charcodeat ();
s + = '//u00 ' + Math.floor (C/16). toString (16) +
(c%). toString (16);
}
}
}
return s + ' ';
Case ' Boolean ':
Return String (strobject);
Default
return ' null ';
}
}

Now we have a way to turn the JSON object into the string we need, and now we go back to modifying the "MyData" variable we defined earlier, we should apply the Json2string method as below.

var = {"Name": "Denny", "Age": MyData, "Shoes": ["Nike", "Osiris", "Etnies"]};
var jsonstr = "p=" + json2string (MyData);

Note below that I prepared the "p=" character in our JSON string, "P" corresponds to the parameter in the "DoWork()" Method, when we rename the parameter to "Dude" (for example DoWork (person Dude ), we must also replace this here with "dude="

Now that we have the query string ready, we see how we invoke the service:
http://www.dennydotnet.com/Service.svc/DoWork/? p={"Name": "Denny", "age": All, "Shoes": ["Nike", "Osiris", "Etnies"]}

You will receive a value that has been processed for URL encoding as follows:
http://www.dennydotnet.com/Service.svc/DoWork/? p=%7b+%22name%22%3a%22denny%22%2c+%22age%22%3a23%2c+%22shoes%22%3a%5b%22nike%22%2c%22osiris%22%2c%22etnies %22%5d+%7d%3b

Immediately after we went to call the "Sendajax ()" JavaScript method, we were now able to debug our service and verify that the data was passed to the service. Such as

Now you only need to implement your own logic in the DoWork () method. Note No matter how you do it on the service side of WCF, it's already done for you.
Now you just need to implement some exception management to make sure you don't get some illegal data, or add some validation, and leave it to yourself ...

jquery calls a WCF service to pass a JSON object

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.