views:

898

answers:

3

In Visual Studio 2010 I created a new Ajax enabled WCF Service

[ServiceContract(Namespace = "TestWCFAjax.Bridge")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Bridge
{
    [OperationContract]
    public string DoWork()
    {
        return "jQuery WCF call without parameters from MVC2 works." ; 
    }

    [OperationContract]
    public string DoWork1(string parm)
    {
        return parm + " jQuery WCF call with parameters from MVC2 fails";
    }

In the Home Controllers Index.aspx view I add the jQuery:

function CallWebMethod() {

$.ajax(
{
     type: "POST",
contentType: "application/json; charset-utf-8",
url: "http://localhost:1452/Bridge.svc/DoWork1",
dataType: "json",
data: '{"parm":"test"}',
error: jqueryError,
success: function (msg) {
     alert("back");
     var divForResult = document.getElementById("test");
     divForResult.innerHTML = "Result: <b>" + msg.d + "</b>";
    }
 })
}

function jqueryError(request, status, error) {
    alert(request.responseText + " " + status + " " + error);
}

(using the built-in Web Server in VS 2010)

When I call DoWork, it works fine. When I call DoWork1 it always returns "error undefined" and the WCF call never happens.

I've tried every combination of: [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] I can think of and it does not help.

I must be missing something simple.

There are MANY posting about how to make this work, and other than the "no parameter" version, none have worked for me.

Can anyone post a sample MVC2 jQuery 1.4 .NET 4.0 WCF VS2010 working sample or spot the likely error?

Thanks.

+2  A: 

contentType: "application/json; charset-utf-8",

should be

contentType: "application/json; charset=utf-8",

Rob
This fixes the problem. To recap:To call an Ajax Enabled WCF service using jQuery in a MVC2/.NET 4.0 project, you do NOT need to do any of the following things people suggest:No Factory="...WebScriptServiceHostFactory" is needed in the .SVCNo [WebInvoke(...)] attribute on the WCF method is needed, just [OperationContract]No changes in the web.config are needed, no webHttp behavior, no changes to the endpoint or any endpoint behavior other than enableWebScriptNo MVC2 IgnoreRoute needed.Thanks Rob!
AUSTX_RJL
A: 

I have been writing and presenting on using jQuery with WCF. The whole MVC does not really matter, or shouldn't matter at least :) I have several post about using it and there is a link for you to download the lastest source from my demo project.

Chris Love
A: 

Hi, I want to know if there is any extra configuration to call an Ajax Enabled WCF service using jQuery in a ASP.NET/.NET 4.0 ??

Thanks.

DIlaang
None that I have found. The accepted answer above was all I needed, everything else works right out of the box.
AUSTX_RJL