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";
}
This is possible, as long as you specify the correct URL. Check out the following form:
and it’s corresponding Javascript:
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:
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.