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
1 Answer
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:
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:

