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
It is a public static method in the code-behind of an aspx page and is callable from the client script. Decorated with the [WebMethod] attribute and rendered as inline JavaScript.
- [System.Web.Services.WebMethod]
- public static string GetEmpName(string empid)
- {
- if (empid == "1")
- return "Mohamed";
- elseif (empid == "2")
- return "Ahmed"; else return "Waleed"; }
Calling Page Method From JavaScript Code
1. Create 2 Text Boxes to simulate and show the results:
- <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>
2. Add JavaScript function to call the page method and return the employee name:
- <script language="javascript" type="text/jscript">
-
- functionGetEmployeeName(parmValueControl ,returnValueControl )
- {
- var ctrl = document.getElementById(parmValueControl);
-
- PageMethods.GetEmpName(ctrl .value, SuccessFunction, FailedFunction, returnValueControl);
- }
-
- function SuccessFunction(empName, returnValueControl)
- {
- var empNameVar =document.getElementById(returnValueControl);
- returnValueControl.value = empNameVar ; }
-
- function FailedFunction(returnedMessage, returnValueControl)
- {
- alert(returnedMessage.get_message());
- }
- </script>
3. Add attributes OnClientClick to our button to call GetEmployeeName Function which call our code behind method:
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!Page.IsPostBack)
- {
- btnGetName.Attributes.Add( "OnClientClick", "javascript:GetEmployeeName('" + txtEmpID.ClientID + "', '" + txtEmpName.ClientID + "')");
- }
- }
4. Don't forget to add this attribute to your script manager:
- <asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server"/>
Try now to run the page and click its button add 1,2 or 3 to the first text box and receive its value in employee name:) Hope this article helps a lot of people trying to pass values from C# code to show in a their html.