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:
2- Add JavaScript function to call the page method and return the employee name :
<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>
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 + "')");
}
}
3- 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.