Invoking WCF service from Javascript

Posted by KhanS on Stack Overflow See other posts from Stack Overflow or by KhanS
Published on 2010-04-14T09:18:07Z Indexed on 2010/04/14 9:23 UTC
Read the original article Hit count: 472

Filed under:
|

I have a asp.net web application, and have some java script code in it. While calling the service I am getting the exception Service1 is undefined. Below is my code.

Service:

namespace WebApplication2
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract(Namespace="WCFServices")]    
    public interface IService1
    {
        [OperationContract]
        string HelloWorld();
    }
} 

Implementation

namespace WebApplication2
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]        
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1 : IService1
    {
        public string HelloWorld()
        {
            return "Hello world from service";
        }
    }
}

ASPX page:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

    <asp:ScriptManager ID="QNAScriptManager" runat="server">
        <Services>
            <asp:ServiceReference Path="~/Service1.svc" />
        </Services>
        <Scripts>
                <asp:ScriptReference Path="~/Scripts/Questions.js" />    
        </Scripts>
    </asp:ScriptManager>
</asp:Content>

Java Script

var ServiceProxy;
function pageLoad() {
    ServiceProxy = new Service1();
    ServiceProxy.set_defaultSucceededCallback(SucceededCallback);
}

function GetString() {
    ServiceProxy.HelloWorld();
}
function SucceededCallback(result, userContext, methodName) {
    var RsltElem = document.getElementById("Results");
    RsltElem.innerHTML = result + " from " + methodName + ".";
    alert("Msg received from service");
}

© Stack Overflow or respective owner

Related posts about wcf

Related posts about JavaScript