I'm going to go right ahead and offer a solution using jQuery, which means you will need to import the library if you haven't already...
Import the jQuery library in your page mark-up:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
Then create another *.js script file (I call mine ExecutePageMethod
, since that is the only method it is going to expose) and import it:
<script type="text/javascript" src="/ExecutePageMethod.js" ></script>
Within the newly added file, add the following code (I remember pulling this from elsewhere, so someone else deserves credit for it really):
function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) {
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
$.ajax({
type: "POST",
url: page + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "json",
success: successFn,
error: errorFn
});
}
You will then need to augment your .NET page method with the appropriate attributes, as such:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string MyMethod()
{
return "Yay!";
}
Now, within your page mark-up, within a script
block or from another script file, you can call the method, like so:
ExecutePageMethod("PageName.aspx", "MyMethod", [], OnSuccess, OnFailure);
Obviously you will need to implement the OnSuccess
and OnFailure
methods.
To consume the results, say in the OnSuccess
method, you can use the parseJSON method, which, if the results become more complex (in the case or returning an array of types, for instance) this method will parse it into objects:
function OnSuccess(result) {
var parsedResult = jQuery.parseJSON(result.d);
}
This ExecutePageMethod
code is particularly useful since it it reusable, so rather than having to manage an $.ajax
call for each page method you might want to execute, you just need to pass the page, method name and arguments to this method.