person person - 1 month ago 3
ASP.NET (C#) Question

Call c# function through javascript

Hello i'm trying to call a c# function with a pass-through variable in JavaScript how would i do that?

<span id="range">0</span>

function showValue(newValue)
i need to Call a csharp function here with the newValue var


Taken from More ideas at Google Search

Step 1: Create an ASP.NET AJAX enabled website. Go to File > New > Website > ASP.NET AJAX-Enabled Web Site. Give the solution a name and location and click Ok.

Step 2: Drag and drop 2 labels and 4 textbox controls. We will be accepting the CustomerID from the user in the 2 textboxes and displaying the ‘ContactName’ in the other two textboxes. The textboxes that will display ‘ContactName’ has some properties set that will make it appear as a label without a border. Just set the BorderStyle=None, BorderColor=Transparent and ReadOnly=True. The markup will look similar to the following:

<form id="form1" runat="server">     

    <asp:ScriptManager ID="ScriptManager1" runat="server"/>


    <asp:Label ID="lblCustId1" runat="server" Text="Customer ID 1"></asp:Label>

    <asp:TextBox ID="txtId1" runat="server"></asp:TextBox><br />

        <asp:TextBox ID="txtContact1" runat="server" BorderColor="Transparent" BorderStyle="None"

            ReadOnly="True"></asp:TextBox><br />

    <br />

    <asp:Label ID="lblCustId2" runat="server" Text="Customer ID 2"></asp:Label>


    <asp:TextBox ID="txtId2" runat="server"></asp:TextBox><br />

        <asp:TextBox ID="txtContact2" runat="server" BorderColor="Transparent" BorderStyle="None"

            ReadOnly="True"></asp:TextBox>&nbsp;<br />



Before moving ahead, we will store our connection string information in the Web.config. Add the following tag below your </configSections> tag. Remember we have created an ‘ASP.NET AJAX enabled website’. The tag </configSections> along with some other tags automatically get added to the web.config.



        <addname="NorthwindConnectionString"connectionString="Data Source=(local); Initial Catalog=Northwind; Integrated Security = SSPI;"/>


Step 3: Currently we will add a method, ‘GetContactName()’ which will accept a CustomerID and return the Contact Name information from the Northwind database, Customer table. We will then transform this method as a PageMethod.


public static string GetContactName(string custid)


    if (custid == null || custid.Length == 0)

        return String.Empty;

    SqlConnection conn = null;



        string connection = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

        conn = new SqlConnection(connection);

        string sql = "Select ContactName from Customers where CustomerId = @CustID";

        SqlCommand cmd = new SqlCommand(sql, conn);

        cmd.Parameters.AddWithValue("CustID", custid);


        string contNm = Convert.ToString(cmd.ExecuteScalar());

        return contNm;


    catch (SqlException ex)


        return "error";








 Public Shared Function GetContactName(ByVal custid As String) As String

    If custid Is Nothing OrElse custid.Length = 0 Then

        Return String.Empty

    End If

    Dim conn As SqlConnection = Nothing


        Dim connection As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString

        conn = New SqlConnection(connection)

        Dim sql As String = "Select ContactName from Customers where CustomerId = @CustID"

        Dim cmd As SqlCommand = New SqlCommand(sql, conn)

        cmd.Parameters.AddWithValue("CustID", custid)


        Dim contNm As String = Convert.ToString(cmd.ExecuteScalar())

        Return contNm

    Catch ex As SqlException

        Return "error"



    End Try

End Function

Step 4: We will now transform this method as a PageMethod and then call this method GetContactName() from client side code; i.e. using JavaScript. To enable the method as a PageMethod, add the attribute [WebMethod] on top of the method:



public static string GetContactName(string custid)




<System.Web.Services.WebMethod()> _

Public Shared Function GetContactName(ByVal custid As String) As String

End Function

At the sametime, add the attribute EnablePageMethods="true" to the ScriptManager as shown below:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>

Step 5: Let us now create the JavaScript that will call this server side code. Add a javascript file called script.js to your solution (Right Click Project > Add New Item > Jscript File > Rename file to script.js). Add the following code to the javascript file.

function CallMe(src,dest)


 var ctrl = document.getElementById(src);

 // call server side method

 PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);


// set the destination textbox value with the ContactName

 function CallSuccess(res, destCtrl)


 var dest = document.getElementById(destCtrl);

 dest.value = res;


// alert message on some failure

 function CallFailed(res, destCtrl)




Step 6: We now need to reference this JavaScript file from our aspx page and invoke the ‘CallMe()’ method whenever the textbox loses focus. To do so:

Add a reference to the javascript file in the body tag as shown below:


<script type="text/javascript" language="javascript" src="script.js">          </script>

<form id="form1" runat="server">     


Step 7: To invoke the methods whenever the textbox looses focus, add these lines of code in the Page_Load() event


if (!Page.IsPostBack)


        txtId1.Attributes.Add("onblur", "javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')");

        txtId2.Attributes.Add("onblur", "javascript:CallMe('" + txtId2.ClientID + "', '" + txtContact2.ClientID + "')");



If (Not Page.IsPostBack) Then

              txtId1.Attributes.Add("onblur", "javascript:CallMe('" & txtId1.ClientID & "', '" & txtContact1.ClientID & "')")

              txtId2.Attributes.Add("onblur", "javascript:CallMe('" & txtId2.ClientID & "', '" & txtContact2.ClientID & "')")

End If

As shown above, we are using the Attributes.Add that lets us add an attribute to the server control’s System.Web.UI.AttributeCollection object. The function ‘CallMe’ kept in the ‘script.js’ file will be invoked. We are passing the source and destination textboxes as parameters. The source textbox will contain the CustomerID. The CustomerID will be looked up in the Customers table and the corresponding ‘ContactName’ will be retrieved in the destination textbox.

Well that is all that is needed to invoke server side code from client side. Run the code. Type ‘ALFKI’ in the first textbox and hit the tab key. You will see that the javascript function goes ahead and calls the PageMethod GetContactName() using PageMethods.GetContactName. It passes the value of the source textbox which contains the CustomerID. The ‘ContactName’ returned is displayed in the second textbox below the first one, in our case the value displayed is ‘Maria Anders’.

Troubleshooting: ‘PageMethods Is 'Undefined'’ error

  1. Try setting EnablePageMethods="true" in the script manager tag

  2. Don't add the javascript references or code in the <head /> section. Add it to the <body> tag.

  3. Page methods needs to be static in code behind.

I hope you have got an idea of how to call server side code using JavaScript. I have used this technique successfully in a few projects and just love and admire PageMethods. I hope you found this article useful and I thank you for viewing it. The source code for this article can be downloaded from here.