Introduction
Today I was trying to access a list of data from my JavaScript code in an ASP.Net page; I Googled for the best solution for this and I found many solutions:
- Using Microsoft AJAX and access web services function.
- Using WCF services and access it directly from JavaScript code.
- Simple solution using the Page method.
Definition for page method
- [System.Web.Services.WebMethod]
- public static string GetEmpName(string empid)
- {
- if (empid == "1")
- return "Mohamed";
- elseif (empid == "2")
- return "Ahmed"; else return "Waleed"; }
- <h3>Enter The Employee ID Here: </h3>
- <asp:TextBox ID="txtEmpID″ runat="server">
- </asp:TextBox> <br />
- <asp:TextBoxID="txtEmpName″ runat="server" ReadOnly="True">
- </asp:TextBox> <br />
- <asp:Button ID="btnGetName" OnClick="return false;"runat="server" Text="Button"></asp:Button>
- <script language="javascript" type="text/jscript">
- // Call the page method and run the success function
- functionGetEmployeeName(parmValueControl ,returnValueControl )
- {
- var ctrl = document.getElementById(parmValueControl);
- // call server side Function
- PageMethods.GetEmpName(ctrl .value, SuccessFunction, FailedFunction, returnValueControl);
- }
- // set the returnValueControl value with the ContactName
- function SuccessFunction(empName, returnValueControl)
- {
- var empNameVar =document.getElementById(returnValueControl);
- returnValueControl.value = empNameVar ; }
- // alert message on some failure
- function FailedFunction(returnedMessage, returnValueControl)
- {
- alert(returnedMessage.get_message());
- }
- </script>
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!Page.IsPostBack)
- {
- btnGetName.Attributes.Add( "OnClientClick", "javascript:GetEmployeeName('" + txtEmpID.ClientID + "', '" + txtEmpName.ClientID + "')");
- }
- }
- <asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server"/>

Ramesh PalaniappanPosted Aug 10, 2016, 10:38 AM
Nice one
kalu singh raoPosted Jul 7, 2016, 1:44 AM
Nice...
Manish Kumar ChoudharyPosted Jan 15, 2015, 12:26 PM
Nice one.
Manish DwivediPosted Jan 31, 2011, 5:55 AM
really it's a simple and easy solution to call server side method through javascript