Calling a web method of a page from javascript on another page

Is it possible to call a method associated with [WebMethod] with javascript on another page? That is, using the following jjery ajax call from a 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";
    }
+5
source share
1 answer

This is possible if you provide 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 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 field to WebMethod on another SampleForm.aspx control. Here is the code of this kind:

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 value sent. The return value is added to the div in Chat.aspx in the success method of the .ajax call.

+8

All Articles