Calling a page's webmethod from javascript on a different page
Asked Answered
R

1

11

Is it possible to call a method attributed with [WebMethod] from javascript on a different page? I.e. using the following jquery ajax call from script on a page called PageTwo.aspx:

    $.ajax(
        {
            type: "POST",
            url: "pageone.aspx/PageOneMethodOne",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg)
                     {
                        //something
                     }
        }
    );

PageOne.aspx.cs containing

    [WebMethod]
    public string PageOneMethodOne()
    {
        return "hello world";
    }
Rachmaninoff answered 12/4, 2012 at 16:39 Comment(1)
I think\ you can as long as you specify the correct url to itSomatic
B
14

This is possible, as long as you specify the correct URL. Check out the following form:

<form id="form1" runat="server">
<div>
    <div id="messages">
    </div>
    <input type="text" id="echo" /><input id="echoSubmit" value="Echo!" type="button"/>
</div>

and it's corresponding Javascript:

<script type="text/javascript">
    $(function () {
        $('#echoSubmit').click(function () {
            var mes = $('#echo').val();
            var jsonText = JSON.stringify({ message: mes });

            $.ajax({
                type: "POST",
                url: "SampleForm.aspx/SendMessage",
                data: jsonText,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    $("#messages").append(msg.d);
                }
            });
        });
    });
</script>

Clicking the echoSumbit button will send the contents of the input box to a WebMethod on another control, SampleForm.aspx. Here is the code-behind of that form:

public partial class SampleForm : System.Web.UI.Page
{
    [WebMethod]
    public static string SendMessage(string message)
    {
        return message;
    }
}

The click handler in Chat.aspx sends the input value to SampleForm.aspx.cs, which returns the sent value. The returned value is appended to a div in Chat.aspx in the success method of the .ajax call.

Backfire answered 12/4, 2012 at 17:28 Comment(3)
You can use a .asmx instead of the code-behind to call a non-static method - #1360753Backfire
Call to web service in WebMethod ?Deluna
requires JQuery ? version ?Deluna

© 2022 - 2024 — McMap. All rights reserved.