[WebMethod]和[AjaxMethod]在Asp.Net中的区别

xsuvu9jc  于 2023-06-25  发布在  .NET
关注(0)|答案(1)|浏览(112)

[AjaxMethod]属性经验的人可以解释一下我们可以使用[AjaxMethod]而不是[WebMethod]的场景。我需要asp.net从JavaScript函数调用www.example.com方法,我在谷歌上搜索过,没有得到任何信息

toiithl6

toiithl61#

我没有看到太多(如果有的话)使用[AjaxMethod]的代码。这需要对ajax.dll的引用,并且在页面加载时,您必须执行一个命令来设置和加载几个移动部件。
WebMethod应该在几乎所有情况下使用,因为:
它使用jQuery.ajax调用可以很好地运行。
WebMethod支持soap、ajax、REST、xml、json和text,并且不需要对代码进行任何更改。
所以,假设你安装了jQuery(不是吗?默认情况下,甚至任何www.example.com项目大约10年以上都包含jQuery)。asp.net project for about 10+ years has included jQuery).
所以,这段代码可以很好地工作:
标记:

<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>

后面的代码是这样的:

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

现在的结果是这样的:

所以,主要的区别是我们没有看到太多的代码或使用[AjaxMethod],使用它需要引用ajax.dll,并且还需要您在页面加载事件中执行一些代码来加载脚本部分以使用AjaxMehods。
我可以安全地建议,当使用WebMethod工作正常时,我看到很少的理由使用[AjaxMethods],并且不需要额外的设置,额外的. dll和额外的页面加载事件代码,AjaxMethods工作。

编辑:使用和调用ascx文件中的webmethod

好吧,这需要“一点点”的额外步骤。
因此,您不能直接使用或调用ascx页面中的Web方法(这是因为这样的页面被假定为现有页面的一部分)。
所以,我把justguageJS变成了UC。因此,要在页面上显示 Jmeter 。
简单的答案???
你不能直接调用ascx方法。因此,您必须在当前aspx页面中放置一个方法和代码存根。
所以,说这个标记:

<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>

所以,在“aspx”页面上,我想调用ascx文件中的web方法。
但是,我有对CURRENT页面的ajax调用,代码看起来像这样:

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

    Return GaugeJS.GetTemp(F).ToString

End Function

所以,我在上面调用ascx中的公共函数(代码后面)。
ascx页面中的web方法是这样的:

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

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

    Return C.ToString

End Function

所以,你可以在ascx控件中有一个web方法,但你永远不能直接调用它-你必须“添加”一个方法到EXISTING页面,然后从当前页面的web方法调用ascx代码。
结果如下:

相关问题