简体   繁体   中英

Call C# method from javascript function

I need to call the c# method from javascript. I need the method to be called only when the javascript button is clicked ie (btnclick()). But Login method gets executed before the onclick of button.

aspx file

    <script type="text/javascript">
    function  btnclick()
    {
    <%=Login() %>;     //calling the c# method
    };
    $(document).ready(function ()
    {

        $(".username").focus(function () {
            $(".user-icon").css("left", "-48px");
        });
    </script>
    <body>
    //contains other elements like username and password text boxes
    <input type="submit" id="submit" name="submit" value="Login" class="button" onclick="btnclick()"/>
    </body>

aspx.cs file

The following c# method have to be called from javascript

 protected void Login()
{
//contains method for authentication
}

Is there any other way to call c# method from javascript.

Your question exposes your lack of knowledge about how websites work. You simply cannot execute C# function form javascript code like:

function  btnclick()
{
<%=Login() %>;     //calling the c# method
};

because javascript is running in the browser and the C# on the server. The reason that your C# Login method was called is that your button is configured to submit the form and the form I suppose is pointing to your server.

Have you tried adding an api controller and putting the method in that? I really like using ProxyApi (it's as simple as adding a NuGet) and it generates clean javascript proxies for you. You'll get it up and running in just a few minutes:

  • Add an ApiController and add the Login method.
  • Add ProxyApi through NuGet and reference it in javascript: [script src="~/api/proxies"][/script]
  • Call your C# method in javascript like this:

    $.proxies.myapi.login(some params).done( function(data) { // done! });

see: https://github.com/stevegreatrex/ProxyApi

You can define c# method as webmethod.

Try It:

[WebMethod]
protected void Login()
{
   //contains method for authentication
}

Thanks.

<script language="javascript" type="text/javascript">
function jsFunction()
{
    document.getElementById('<%=lbSubmit.ClientID%>').click();
}
</script>





<asp:LinkButton  ID="lbSubmit" runat="server" Text="Update Files" 
onclick="cshapbottun_Click" ></asp:LinkButton>



C# code
protected void cshapbottun_Click(object sender, EventArgs e)
{
//    DoSomething;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM