In practical situations we may need to pass parameters to the server-side from client-side. How can we do that using the same example described in the above mentioned blog.
Let's assume that we need to add two numbers. The numbers are going to input by the user via a text input in HTML.Addition will be done in server-side (by a C# method in ASP.net) after we click a button. (Ajax technology will be used)
- Define 2 text inputs in HTML
<input id="Text1" type="text" />
<input id="Text2" type="text" />
- Define a HTML button and calls to a function in the onclick event
<input id="Button1" type="button" value="button" onclick="inputNum()"/>
- Define a ASP.net script manager in client-side (just drag and drop the controller from the tool box)
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True" EnablePartialRendering="true"> </asp:ScriptManager>
- Define following functions in the client-side using Javascript. (Here I use an array to pass the two numbers as arguments to the server-side method)
function inputNum() {
var nums = new Array();
nums[0] = document.getElementById("Text1").value;
nums[1] = document.getElementById("Text2").value;
GetInputNumFromServer(nums);
}
function GetInputNumFromServer(numsArray) {
PageMethods.GetSum(numsArray, OnSuccess, OnError);
return false;
}
function OnSuccess(response) {
alert(response);
}
function OnError(error) {
alert(error);
}
- Define the C# method in the server-side. (You have to use the System.Web.Services reference)
[WebMethod]
public static int GetSum(int[] arr)
{
return arr[0]+arr[1];
}
That's All.
No comments:
Post a Comment