calling ASP function from javascript

hello i have this question i was trying to find a way to call a javascript function from asp controllers and i did here is the code :

    <script type="text/javascript">
      function hello() { 
        alert("hello world")
    }
</script>
<  /head>
 <body>
<form id="form1" runat="server">
<div>
    <asp:Button ID="buttonme" runat="server" OnClientClick="javascript:hello()" 
 Text="click" />

now lets say i have this code behind function

    Public Sub msg()
      MsgBox("hello world")
    End Sub 

and i want to call it from a javascript function so it will be like controller—-call—> javascript —call—>code behind

is there is a way to do this

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Define your method in a class somewhere in your web application.

[System.Web.Services.WebMethod]
public static string Msg()
{
     return "Hello world";
}

Add a script manager with EnablePageMethods=true in your aspx page

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

Call the method in javascript

<script language="javascript" type="text/javascript">
    PageMethods.Msg(onSuccess);
    function onSuccess(response)
    {
        alert(response);
    }
</script>

Solution 2

You must use AJAX in some form and expose the ASP.NET method you want to call via HTTP.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply