locked
How to call a C# code behind method from a Java Script function RRS feed

  • Question

  • User-1682007629 posted

    Is their a way to call a C# code behind method from a Java Script function? Can someone show me how to do it?

    Example:

    <html>
    <head>
    <script type="text/javascript">
    function displaymessage()
    {
       // In this function call a C# method named DisplayInformation(); 

    }
    </script>
    </head>

     

    in C# :

     

    void DisplayInformation(void){

     // Do something in this C# method

    }

    Thursday, April 23, 2009 11:21 PM

Answers

  • User-219472588 posted

     Hi brgdotnet,

    Very first thing is if you want to call server side function using server tag inside javascript then it's not possible. You must eigher call Web Service method or page using AJAX call.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 24, 2009 1:36 AM
  • User-48124152 posted

     hello,

    you can try something like this

     .aspx

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
        <script type="text/javascript" language="javascript">
            function TestCodeBehind()
            {
                document.getElementById('<%= Label1.ClientID %>').innerHTML = '<%= CodeBehind() %>';
               return false;
            }
            
             function TestCodeBehind2()
            {
                document.getElementById('<%= Button2.ClientID %>').click(); 
              //  return false;
            }
    
    </script>
    
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <input id="Button1" type="button" value="Sample One" onclick="javascript:TestCodeBehind()" />
            <input id="Button3" type="button" value="Sample two" onclick="javascript:TestCodeBehind2()" />
            <asp:Button ID="Button2" runat="server" Text="" OnClick="ClickedME"  />
            <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
        </div>
        </form>
    </body>
    </html>
    
    .aspx.cs 
    protected void Page_Load(object sender, EventArgs e)
    {
    Button2.Attributes.Add("style", "visibility :hidden");
    }

    protected string CodeBehind()
    {
    return "this is a string from C# code behind " + DateTime.Now.ToString();
    }
    protected void ClickedME(object sender, EventArgs e)
    {
    Label1.Text = "You clicked this button on " + DateTime.Now.ToString();
    }
     
      
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 24, 2009 2:24 AM

All replies

  • User-1659704165 posted

     Hi,
    U can call Session  or Control in javscript
    in follwing way..

    '<%=Session["MyName"]%>'
    '<%=Label1.text%>'
    just Try
    //Inline code
    public string Mynamestring()
    {
       string strName = "";
      return strName = "avinash";
    }
    //Method calle in javascript

    '<%=Mynamestring()%>'
    Hop it help

    Friday, April 24, 2009 12:28 AM
  • User100899815 posted

    Options...

     

    1. Use a HiddenField control and set its value using javascript fuction and check its value on post back to trigger a C#  method. You can use the ClientID property of the control class to find the control in your javascript code..
    2. Use window.location method in you javascript and pass a some parameters  and inovke  your methods by checking for those in your c# code behind..

     

    Friday, April 24, 2009 12:33 AM
  • User-1419202310 posted

    What actually you want to do in that method.

    If the method you are saying is a server side event of a control, you can not call a server side event from client side using java script.

    Friday, April 24, 2009 12:43 AM
  • User1292693938 posted

    Hi,

    Make the method that you want to access client side as public and then get method at client side as:

    <%=MethodName()%>

    Thanks,

    Khushboo Nayak

    Please Mark as Answered if this helps you.

    Friday, April 24, 2009 1:00 AM
  • User-40550723 posted

     You can use page method approach to call C# methods from javascript.

    check this link

     

    http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx
      
    Friday, April 24, 2009 1:04 AM
  • User89132282 posted

     

    Hi there, you can do it using pagemeathod. Go through the following url for full description.

    http://www.dotnetcurry.com/ShowArticle.aspx?ID=109&AspxAutoDetectCookieSupport=1

    Friday, April 24, 2009 1:26 AM
  • User-219472588 posted

     Hi brgdotnet,

    Very first thing is if you want to call server side function using server tag inside javascript then it's not possible. You must eigher call Web Service method or page using AJAX call.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 24, 2009 1:36 AM
  • User-48124152 posted

     hello,

    you can try something like this

     .aspx

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
        <script type="text/javascript" language="javascript">
            function TestCodeBehind()
            {
                document.getElementById('<%= Label1.ClientID %>').innerHTML = '<%= CodeBehind() %>';
               return false;
            }
            
             function TestCodeBehind2()
            {
                document.getElementById('<%= Button2.ClientID %>').click(); 
              //  return false;
            }
    
    </script>
    
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <input id="Button1" type="button" value="Sample One" onclick="javascript:TestCodeBehind()" />
            <input id="Button3" type="button" value="Sample two" onclick="javascript:TestCodeBehind2()" />
            <asp:Button ID="Button2" runat="server" Text="" OnClick="ClickedME"  />
            <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
        </div>
        </form>
    </body>
    </html>
    
    .aspx.cs 
    protected void Page_Load(object sender, EventArgs e)
    {
    Button2.Attributes.Add("style", "visibility :hidden");
    }

    protected string CodeBehind()
    {
    return "this is a string from C# code behind " + DateTime.Now.ToString();
    }
    protected void ClickedME(object sender, EventArgs e)
    {
    Label1.Text = "You clicked this button on " + DateTime.Now.ToString();
    }
     
      
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 24, 2009 2:24 AM
  • User854688209 posted

    Create a button like below in aspx page. 

    <asp:Button ID="Button1" runat="server" OnClientClick="CallCodeBehind" Text="Upload" />

     Add below javascript in aspx page:

    <script type = "text/javascript">

    function CallCodeBehind()

    {

    var a = '<%=CallFromJS()%>';

    }

    </script>

    Put the below method in codebehind

    public string CallFromJS()

    {

    string str = "testing";

    return null;

    }

    Friday, April 24, 2009 2:39 AM
  • User-219472588 posted

    BryianTan is right. But based on my experience calling .click() event do postback but doesn't fire click event of button (when you have ScriptManager in Page) . In that situation you can make use of __doPostBack method like

    __doPostBack('<ButtonId>','') ;

    Friday, April 24, 2009 2:56 AM
  • User-656168988 posted

    Hi Sumit,

     

    Its working but its event is firing on load & post back event.

    In my scenario- I'm using gridview & one of column have link button, when user click on link of gridview column then it will change into text box, Now user can make any changes in text box data where user outing I mean text box lost focus then this javascript method called (on onBlur)with return certian parameter. These parameter I need into code behind OR Call code behind function in C#  to update database records.

    Almost we have reach ...& finally  I need your push up to complete may problem.

     

    Thank you in Advance

    Anwar

    Saturday, July 11, 2009 2:26 AM
  • User-656168988 posted

    Hi,

    How to do __doPostBack in this case?

    plz little explain more

     

     

    Thankks

     

     

    Saturday, July 11, 2009 2:29 AM
  • User427185885 posted

    Could you please explain your solution.

    Saturday, August 8, 2009 12:56 AM
  • User1969553586 posted

    aspx Designer:

    <html>
    <head>
        <title></title>
    </head>
    <body>
    <script language="javascript" type="text/javascript">
        function NewPop(Src) {       
            PageMethods.ShowMe();       
        }
    </script>


        <asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
        </asp:ScriptManager>
        <asp:Button ID="Button1" runat="server" Text="Login" OnClientClick="NewPop(this)" />
    </body>
    </html>

     


    aspx.cs Code:

    using System.Web.Services;

    namespace CallfromJScript
    {
        public partial class _Default : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
     {
     }

     //The Function You Want to call from JScript
            [WebMethod]
            public static void ShowMe()
            {
                ucPopUpContainer._strPopUpType = "2";
                ucPopUpContainer._strWidth = "325";
                ucPopUpContainer._strHeight = "400";
                ucPopUpContainer._strUserControlName = "UserControl2";
                ucPopUpContainer.InstanceRef.ShowPopUp();           
            }
        }
    }

     

    The above scenario work for UserControl tooo. If it is a UserControl use the html content mentioned above in ascx and the code content in the page in which the user control is used.

    Be sure that the function is static and EnablePageMethods="true".

    Regards

    Akhil

    Mark as answer if helpfull

    Wednesday, September 16, 2009 4:25 AM
  • User-1388164259 posted

     

    <script type="text/javascript">

     PageMethods.SetLabel(myValue, onSuccess, onFailure);

     

    }

     

    document.getElementById(

    }

     

    alert(

    }

     

     

     

    function Sample() {var myValue = document.getElementById('TextBox1').value;function onSuccess(result) {'Label1').innerHTML = result;function onFailure(error) {'fail');</script>

     

     

     

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

     

    </asp:ScriptManager>

     

    <div>

     

    <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>

     

    <br />

     

     

    <br />

     

     

    <asp:Label

     

     ID="Label1" runat="server" Text="Label"></asp:Label>

     

    </div>

     

     

     

    {

     

    {

    TextBox1.Attributes.Add(

    }

    }

    [System.Web.Services.

     

    {

     

    protected void Page_Load(object sender, EventArgs e)if (!IsPostBack)"onkeyup", "Sample();");WebMethod ]public static string SetLabel(string myValue)//Do your logic here

     

    }

    return myValue;

    Thursday, December 2, 2010 12:18 AM