How to use a [WebMethod] in server script blocks in the aspx page?

爱⌒轻易说出口 提交于 2019-12-10 21:47:02

问题


I'm trying to create a simple .Net 3.5 page thas has some HTML and a WebMethod. When I try to call my WebMethod from my browser, but it keeps returing the page. Any ideas how to get it to work?

This is my code:

<%@ Page Language="C#" Inherits="CFW.WebUI.Page" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    [System.Web.Services.WebMethod]
    public static string Test()
    {
        return "Hola!";
    }

</script>
<html xmlns="http://www.w3.org/1999/xhtml">
...
</html>

Note: I'm not using Ajax.Net. I just want to call the WebMethod from the client (using jQuery).


回答1:


The way to do that is as follows:

[WebMethod]
public static string SayHello()
{
     return "Hola";
}

In your page you need to add a ScriptManager and set the EnablePageMethods property to true as so:

<asp:ScriptManager id="sMgr" runat="server" EnablePageMethods="True" />

All that does is that it creates a Javascript proxy class on your page that will allow you to call you SayHello method by just doing the following in Javascript:

function InvokeSayHello()
{
     alert(PageMethods.SayHello()); //Will alert 'Hola'
}



回答2:


instead of writing

    [System.Web.Services.WebMethod]

use

    [WebMethod]
    [System.Web.Script.Services.ScriptMethod]



回答3:


I'm not sure if this works without the ScriptManager, but it is definately possible to call a PageMethod without using the PageMethod keyword. You can call your ASP page just like any other webservice, eg. yourpage.aspx/MethodName. The function should be decorated with a [WebMethod] attribute, there is no need to put the [ScriptMethod] tag or anything on the page class itself. I do notice I POST data to these functions rather than GET, but I am not sure if this is required.




回答4:


You might want to add [System.Web.Script.Services.ScriptMethod()] to your method as well :

**

http://geekswithblogs.net/frankw/archive/2008/03/13/asp.net-ajax-callbacks-to-web-methods-in-aspx-pages.aspx



来源:https://stackoverflow.com/questions/10650969/how-to-use-a-webmethod-in-server-script-blocks-in-the-aspx-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!