views:

274

answers:

3

What is the proper way to call a ASMX Web Service with MicrosoftAjax.js if your just including the JavaScript in static HTML?

What I have so far:

<html>
<head>
    <title>Testing</title>
    <script type="text/javascript" src="scripts/MicrosoftAjax.js"></script>
    <script type="text/javascript">
        function testCallSoap() {
            // in here I want to call the default HelloWorld() method
            // it is located at ~/MyTestService.asmx
        }
    </script>
</head>

<body>
    <div>
        <span onclick="testCallSoap();">test</span><br />
    </div>
</body>
</html>
+1  A: 

I've honestly never called a webservice without a script manager, but:

In your webservice, you need to make sure that your WebService class uses the [ScriptService] attribute. Then you can include this js file: MyService.asmx/js.

[ScriptService]
public class MyService : WebService
{
    [WebMethod]
    public string Foo()
    {
         return "bar";
    }
}

This will make it work with JSON... See this article: http://geekswithblogs.net/JuanDoNeblo/archive/2007/10/24/json_in_aspnetajax_part2.aspx

Not really a complete answer, but I hope it gets you moving in the right direction.

Darthg8r
+1 I have seen this approach. I guess you could just put in something like this in the first few script refs <script src="SomeService.asmx/js"></script> This will bring in the proxy.
tyndall
+1  A: 

You can use the WebServiceProxy's static invoke() method:

Sys.Net.WebServiceProxy.invoke("foo.asmx", "HelloWorld", false, { param: 'foo' }, onSuccess, onFailed);

http://msdn.microsoft.com/en-us/library/bb383814.aspx

The path needs to be a client usable one, so "~/" won't work, for example.

InfinitiesLoop
+1 Didn't even know this was available. Nice.
tyndall
A: 

If you're already using Ajax.Net, it's as easy as registering the WebService with the ScriptManager. This is untested, I just typed it from memory to give you the idea.

Web Service:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class MyTestService: WebService
{
    [WebMethod(true), ScriptMethod]
    public string DefaultMethod(string msg)
    {
        return "ZOMG HI THERE! You said: " + msg;
    }
}

Code Behind On Calling Page

partial class Test {
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager.GetCurrent(Page).Services.Add(new ServiceReference("~/MyTestService.asmx"));

    }
}

Javascript on Calling Page:

function testCallSoap() {
   MyTestService.Test("Foobar!", onTestSuccess, onTestFail);
}
function onTestSuccess(result) {
   alert(result);
}
function onTestFail(result) {
   alert("omg fail!");
   alert(result._message);
}
blesh