ajax call to wcf from asp.net mvc
ajax, asp.net-mvc, wcf
Solution
So you are trying to consume a WCF service from JavaScript?
The first problem I see is, your service is not yet ready to be consumed from JavaScript :(. You have to make the following changes..
Configure the `Service1` class with the `AspNetCompatibilityRequirements` behavior.
Mark the service method `HelloWorld` in interface with `WebGet` attribute. [You need reference to `System.SericeModel.Web` assembly]
After making the two changes..
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string HelloWorld(string personName);
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public string HelloWorld(string personName)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
// you are not returning data in proper JSON format, wrap the text in
// an anonymous object before serializing.
return serializer.Serialize(new { text = "Hello " + personName });
}
}
Next..
Configure `webHttpBinding` for the service (Make sure you change the service and contract names!).
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP" />
</webHttpBinding>
</bindings>
<services>
<service name="MvcApplication3.Service1">
<endpoint address="" binding="webHttpBinding"
bindingConfiguration="webHttpBindingWithJsonP"
contract="MvcApplication3.IService1"
behaviorConfiguration="webHttpBehavior"/>
</service>
</services>
</system.serviceModel>
So now the service is ready!
Lets do the changes in the client-side (You are getting some data from the service so why POST?)
<script type="text/javascript">
var personName = "John";
var dataIn = '{' + '"input":"' + personName + '"}';
$.ajax({
url: "http://localhost:50623/Service1.svc/HelloWorld",
type: "GET",
contentType: "application/json; charset=utf-8",
data: dataIn,
dataType: "json",
success: function (data) {
var jsonData = JSON.parse(data);
$("#response").html(jsonData.text);
},
error: function (error) {
alert("Error: " + error);
}
});
</script>
Till now I've assumed that both the WCF service and the MVC app are running in the same domain.
But if that's not the case then you will gete a `405`(Method Not Allowed) error due to CROSS-DOMAIN BARRIER.
There are different ways to overcome this problem!
1. Use JSONP
In this case you have to set the `crossDomainScriptAccessEnabled` property to `true` in the binding and you have to make JSONP calls from jQuery.
<binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
Then change the `dataType` from `"json"` to "`jsonp"` in the `$.ajax` method.
<script type="text/javascript">
var personName = "John";
var dataIn = '{' + '"input":"' + personName + '"}';
$.ajax({
...
dataType: "jsonp",
...
});
</script>
2. Using CORS
Refer this..
http://www.w3.org/TR/cors/
https://developer.mozilla.org/en/http_access_control
Problem
I have two apps. The first is WCF Service, the second is asp.net MVC 3 app. In the WCF app I have a interface: ``` [ServiceContract] public interface IService1 { [OperationContract] string HelloWorld(string personName); } ``` And a class: ``` public class Service1 : IService1 { public string HelloWorld(string personName) { JavaScriptSerializer serializer = new JavaScriptSerializer(); return serializer.Serialize("Hello " + personName); } } ``` Now, in the asp.net mvc app I want call this method via Ajax: ``` <script type="text/javascript"> var personName = "John"; var dataIn = '{' + '"input":"' + personName + '"}'; $.ajax({ url: "http://localhost:7215/Service1.svc/HelloWorld", type: "POST", contentType: "application/json; charset=utf-8", data: dataIn, dataType: "json", success: function (data) { var object = JSON.parse(data.d); if (object.Error == '') { $("#response").html(object); } }, error: function (error) { alert("Error: " + error); } }); </script> ``` But in the Firebug I get error: `400 Bad Request`. How to call `HelloWorld` method properly? Thanks.