HTML and CSS Reference
In-Depth Information
TemperatureData Convert(TemperatureData t);
}
public class Service : IService
{
public TemperatureData Convert(TemperatureData t)
{
if (t.Unit == "C")
{
t.Value = (t.Value * 1.8m) + 32;
t.Unit = "F";
}
else
{
t.Value = (t.Value - 32) / 1.8m;
t.Unit = "C";
}
return t;
}
}
}
The
TemperatureData
class represents the data contract of the WCF service and contains two data
member properties:
Value
and
Unit
. The
IService
interface represents a service contract for the service
and defines a single method
Convert()
. The
Convert()
method accepts a
TemperatureData
object and
returns a
TemperatureData
object after converting the temperature value to the other scale.
Notice that
Convert()
is decorated with an
[WebInvoke]
attribute. Due to this attribute,
Convert()
becomes callable from the client-side jQuery code. The
RequestFormat
and
ResponseFormat
properties of
the
[WebInvoke]
attribute specify JSON as the communication format during request and response,
respectively. The
Method
property specifies that
Convert()
can be invoked by HTTP
POST
requests. The
Service
class implements
Convert()
. The
Convert()
method checks the
Unit
of the incoming
TemperatureData
object and, depending on the
Unit
, converts the
Value
to the other scale.
The
Service
class's
Convert()
method can be called using jQuery's
$.ajax()
function as shown in
Listing 2-16.
Listing 2-16.
Using
$.ajax()
to Call the WCF
Service
Convert()
Method
$(document).ready(function () {
$("#Button1").click(function () {
url = "Service.svc/Convert";
data = '{"Value":"' + $("#Text1").val() + '","Unit":"' + $("#Select1").val() + '"}';
$.ajax({
type: "POST",
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError
})
});
});