0

Can someone who has experience with [AjaxMethod] attribute please explain which scenario we can use [AjaxMethod] over [WebMethod]. I need to call asp.net method from javascript function I googled and did not get any much information

AMDI
  • 895
  • 2
  • 17
  • 40

1 Answers1

1

I not seen much (if any) posted code for using [AjaxMethod]. That requires a reference to the ajax.dll, and on page load you have to execute a command to setup and load a few moving parts.

WebMethod should be used in near all cases, since:

It works and plays nice using a jQuery.ajax call.

WebMethod supports soap, ajax, REST, xml, json, and text, and DOES so without ANY changes to your code.

So, assuming you have jQuery installed (don't we all???, and by default even any asp.net project for about 10+ years has included jQuery).

So, then this code can work just fine:

Markup:

<h4>Select fighter</h4>
<asp:DropDownList ID="cboFigher" runat="server" Width="300"
    DataTextField="Fighter"
    DataValueField="ID"
    onchange="mychange(this)">
</asp:DropDownList>
<br />


<div class="mybox" style="float: left; border: solid 1px">
    <div style="text-align: center; padding: 2px 10px 12px 10px">
        <h3 id="Fighter" runat="server"></h3>
        <asp:Image ID="Image2" runat="server"
            Width="180" Height="120" />
        <h4>Engine</h4>
        <asp:Label ID="EngineLabel" runat="server" Text="" />
        <h4>Description</h4>
        <asp:Label ID="DescLabel" runat="server" Width="400px"
            Text="" Style="text-align: left" Font-Size="Large" />
    </div>
</div>

<script>

    function mychange(myitem) {
        // get data record from server, update
        // dom values
        var iPK = myitem.value
        $.ajax({
            type: "POST",
            url: "FighterOneAJ.aspx/GetFighter",
            data: JSON.stringify({ PK: iPK }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (rData) {
                var F = rData.d
                $('#Image2').attr("src", F.ImagePath)
                $('#Fighter').text(F.Fighter)
                $('#EngineLabel').text(F.Engine)
                $('#DescLabel').text(F.Description)

            },
            failure: function (rData) {
                alert("error " + rData.d);
            }
        });

    }

</script>

And the code behind is this:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not IsPostBack Then

        cboFigher.DataSource =
                MyRst("SELECT ID, Fighter FROM Fighters ORDER BY Fighter")
        cboFigher.DataBind()
        cboFigher.Items.Insert(0, New ListItem("Select Fighter", "0"))

    End If

End Sub


<WebMethod()>
Public Shared Function GetFighter(PK As String) As clsFigher

    Dim OneFigher As New clsFigher

    OneFigher.ID = PK
    Return OneFigher


End Function


Public Class clsFigher
    Public Fighter As String
    Public Engine As String
    Public Thrust As String
    Public Description As String
    Public ImagePath As String
    Private m_id As Integer

    Public Property ID As Integer
        Get
            Return m_id
        End Get
        Set(value As Integer)
            m_id = value

            Dim cmdSQL As New _
                    SqlCommand("SELECT * FROM Fighters WHERE ID = @ID")

            cmdSQL.Parameters.Add("@ID", SqlDbType.Int).Value = m_id

            With MyRstP(cmdSQL).Rows(0)
                Fighter = .Item("Fighter")
                Engine = .Item("Engine")
                Thrust = .Item("Thrust")
                Description = .Item("Description")
                ImagePath = Replace(.Item("ImagePath"), "~/", "../")

            End With
        End Set
    End Property

End Class

And now the result is this:

enter image description here

So, the main difference is we don't see much code or use of [AjaxMethod], and use of that requires a reference to the ajax.dll, and also requires that you on page load event execute some code to load the script part to use AjaxMehods.

I can safe suggest that I see VERY little reason to use [AjaxMethods] when using WebMethod works fine, and does not require extra setup, extra .dll, and extra code on page load event for AjaxMethods to work.

Edit: Using and calling a webmethod in a ascx file

Ok, this takes a "bit" of a extra step.

So, you can NOT directly use nor call a web method in a ascx page (this is because such pages are ASSUMED to be part of a existing page).

So, I turned the justguageJS into a UC. So, to display a gauge on a page.

The simple answer???

You can't really directly call a ascx method. So you MUST place a method and code stub in the current aspx page.

So, say this markup:

        <div style="float:left">
            <uc1:GaugeJS runat="server" 
                ID="GaugeJS1" 
                Donut="true" 
                Label="Tempature\nF"
                Max="80" 
                Min="0" 
                Value=0
                Counter="true"
                FontColor="black"
                Width="100"
                />
        </div>

        <div style="float:left">
            <uc1:GaugeJS runat="server" 
                ID="GaugeJS2" 
                Donut="true" 
                Label="Tempature\nC"
                Max="80" 
                Min="0" 
                Value="0" Counter="true"
                FontColor="black"
                Width="100"
                />
        </div>
        <br />

        <asp:Button ID="cmdGetFuel" runat="server" 
            Text="Convert to C"
            CssClass="btn"
            OnClientClick="webcalltest();return false"
            />

        <script>
            var F = 68

            function mytest() {
                GaugeJS1.refresh(F, 80, 0)
            }

            function webcalltest() {
                $.ajax({
                    type: "POST",
                    url: '<%= ResolveUrl("~/Controls/TestGuage.aspx/GetTemp") %>',
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({F : F }),
                    success: function (data) {
                        var C = data.d
                        GaugeJS2.refresh(C, 80, 0)
                    },
                    error: function (msg) {
                        alert("Failed: " + msg.status + ": " + msg.statusText);
                    }
                });
            }


            $(window).on('load',function () {
                GaugeJS1.refresh(F, 80, 0)
            });

        </script>

So, on the "aspx" page, I want to call a web method in the ascx file.

but, I have the ajax call to CURRENT page, and the code then looks like this:

<WebMethod()>
Public Shared Function GetTemp(F As Integer) As String

    Return GaugeJS.GetTemp(F).ToString

End Function

So, I THEN in above call the public function in the ascx (code behind).

The web method in the ascx page is thus this:

<WebMethod>
Public Shared Function GetTemp(F As Integer) As String

    Dim C As Double
    C = (F - 32) / 1.8

    Return C.ToString

End Function

So, you CAN have a web method in the ascx control, but you can never call it directly - you have to "add" a method to the EXISTING page, and then call the ascx code from the current page's web method.

The result looks like this:

enter image description here

Albert D. Kallal
  • 42,205
  • 3
  • 34
  • 51
  • D.Kallal ,Thanks for explaining.Unfortunately in my scenario I am trying to call ascsx.cs method from Javascript file which is common file and the code snippet is not working when tried to apply in myscenario.Please find my query in more detail and explain how to call [AjaxMethod] in Pageload event.as its very old setup thtat we are dealing with .https://stackoverflow.com/questions/76519321/call-asp-net-method-from-javascript-file – AMDI Jun 22 '23 at 19:52
  • Please let me know the link of documentation for [AjaxMethod] atrribute – AMDI Jun 22 '23 at 21:20
  • 1
    It is REALLY old stuff. I don't think much of any references exist much more. We talking about 2005-2007 era when that was last used. (that is a whopping 18 years ago!!). This explains why you don't see many if any examples at a all, since you have to go back WAY too far back in history. There is a working example posted here that uses AjaxMethod, and note the use of page load. You also have to reference ajax.dll in your project. https://www.codeproject.com/articles/17543/sample-code-for-ajax-in-c-net-asp-net-with-ajax-dl – Albert D. Kallal Jun 22 '23 at 22:01
  • I not even sure you could get the above example to work. However, while [AjaxMethod] is like cave man history type of stuff, the use of PageMethods in a page is worth consideration, since the calling format is rather nice and clean. However, once you have one jQuery ajax call setup and working, then I just cut + paste it, so again it not a huge deal here. However, even jQuery .ajax calls can be replaced with page methods, but you STILL tag the code behind with Webmethod, and not use AjaxMethod anymore. So, AjaxMethod was the "first" example of asp.net adopting ajax - it out of date now – Albert D. Kallal Jun 22 '23 at 22:03
  • Calling web methods in an ascx file? they STILL work if you change that over to WebMethods and use a jQuery ajax call. So, I use and call webmethods from ascx pages all the time - syntax of the jQuery is 100% the same as posted above. I tend to not use ascx pages unless the webmethod is to be called from MORE then one page -- the current page. So, for any webmethod for a given web page, if that is the ONLY page that calls the webmethod, I place it in the aspx page. But, calling webmethods in ascx pages works just fine. So, I would change those tags in code. (so your dealing with old code). – Albert D. Kallal Jun 22 '23 at 22:07
  • Thanks a lot for sharing so much useful information. But when I am trying to call usercontrol method from javscript.I am getting error like "Uncaught ReferenceError: FormUI is not defined" not sure how to call usercontrol from a separate js file – AMDI Jun 23 '23 at 03:23
  • see my edit, above, you can "never" call a web method directly from a ascx page. Since that UC will be dropped into a existing page, then that's not really much of a issue. You can call bits and parts of JavaScript code included in the ascx page, but you can't call code behind web method from the ascx page. But, a button click can, or do as I did above, add a webmethod to the CURRENT page, and then call the ascx code stub that way. – Albert D. Kallal Jun 24 '23 at 00:49