Friday 9 January 2009

Web methods - calling code-behind methods from the client

Web methods are really simple to use. First up you need to make sure in your page's ScriptManager you have the EnablePageMethods property set to true.

Next write your method in the code-behind for your page, making sure to put the WebMethod attribute on it:

[WebMethod]
public string GetMyData(string args)
{
// Do something
return "blah blah";
}

Now in your .aspx page add a function which will call this method:

<script language="javascript">

function getDataFromServer()
{
var args = 'blah'; // the arguments for the server-side method
// you could use JSON here to pass several args

PageMethods.GetMyData(args, OnSucceeded, OnFailed);
}

function OnSucceeded(result)
{
// Here I'm just writing out the result to a textbox
$('#txtOutput').val(result);
}

function OnFailed(error, userContext, methodName)
{
alert("Failed");
}
</script>


And then all you need to do is stick a call to your javascript method somewhere, eg. on a button click:

<input type="submit" text="Do something" onclick="getDataFromServer();">

No comments: