使用AjaxPro,js调用后台方法

来源:互联网 发布:sql区分二范式和三范式 编辑:程序博客网 时间:2024/04/30 00:55

在ajax应用中,有时会需要在前台某个时刻调用后台的方法,这可以借助AjaxPro轻松实现。

 

1.到http://ajaxpro.info下载最新包。我下的是9[1].2.17.1版。里面包含4个dll和一个xml。

 

2.在使用之前,需要添加AjaxPro.dll的引用,其他的dll不要添加,否则会引起冲突!

 

3.修改web.config
在system.web节点下添加:

<system.web>
    <httpHandlers>
      <add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro.2"/>
    </httpHandlers>
 
4.在.NET方法中向客户端注册javascript,并将要调用的.NET方法添加AjaxMethod属性
以下为引用的内容:
namespace MyDemo
{
public class _Default
{
    protected void Page_Load(object sender, EventArgs e)
    {
      AjaxPro.Utility.RegisterTypeForAjax(typeof(_Default));
    }

    [AjaxPro.AjaxMethod]
    public DateTime GetServerTime()
    {
      return DateTime.Now;
    }
}
}
 
5.在客户端用javascript调用服务器端的方法:
function getServerTime()
{
MyDemo._Default.GetServerTime(getServerTime_callback); // asynchronous call
}

// This method will be called after the method has been executed
// and the result has been sent to the client.
function getServerTime_callback(res)
{
alert(res.value);
}
就这样,简单的几步,就已经完成了。在客户端用javascript异步调用服务器端的C#方法,并可以得到服务器端的返回值,这个值会传到javascript,javascript可以处理这个返回的值,这个示例是官方给出的示例,服务器端返回的是一个DateTime,不过,我们也可以返回复杂的数据类型,像DataTable之类,总之,AjaxPro把Ajax搞得很简单。
原创粉丝点击