javascript直接调用asp.net方法的技术 ——介绍pixysoft.ajax技术


前言

  本技术完全开源,请各位兄弟随便修改、使用,但是必须能够保留相关版权的说明;我的小小技术能在您的项目中使用,是我的光荣,希望不要破灭了我仅存的自豪感,衷心感谢,在此鞠躬!

  本技术主要基于.net 2.0,提供asp.net页面的javascript直接通过ajax调用服务端的c#方法,完全打通javascript往asp.net的最后防线。

  本技术实在开发pixysoft.framework.neobes.jsons中用到的一项技术。而jsons框架主要负责面向异构网站提供基于jsons的数据库访问。

  技术演示

  aspx页面简介:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="Pixysoft.Ajax" Namespace="Pixysoft.Framework.Noebe.Jsons.WebControls"
    TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>pixysoft.ajax</title>
    <script type="text/javascript">
    var code=1;
    function ServerMethodCallback(value)
    {
    code = value;
    Message1.innerText = value;
    }    
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <cc1:PixysoftAjaxBase ID="PixysoftAjaxBase1" runat="server" />
            <br />
            result: <span id="Message1">0</span>
            <input type="button" value="让我们回调吧!" onclick="ServerMethod(code)" id="Button1" />
        </div>
    </form>
</body>
</html>
后台代码简介:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    public int ServerMethod(int value)
    {
        return value * 2;
    }
}

  1. 页面有个htmlbutton, 点击会激活 ServerMethod这个方法

  2. 后台会处理这个方法,回调页面的ServerMethodCallback,同时把运算结果传入

  3. 运行结果就是不断结算 code *2,并显示在页面的<span id="Message1">里面。

  4. 如果服务端的方法不需要返回参数,那么可以不写ServerMethodCallback.

  教程说明

  1. 首先需要在服务端声明一个public的方法, 例如public int ServerMethod(int value); 可以无返回值.

  2. 在javascript里面直接使用服务端声明的方法,例如onclick="ServerMethod(code)" ,区分大小写。

  3. 如果服务端方法有返回值,那么需要在javasccript声明一个回调方法,命名规则是服务端方法+Callback,例如:function ServerMethodCallback(value)

  4. 完成

  注意事项

  1. 非常悲哀,调用过程不支持session / cache 等,就是完全的无状态。这是由于asp.net的一个bug造成的。具体:


  http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=104259

  2. 同样悲哀,调用的方法不支持直接执行,只能通过event激活,例如一下是个无效调用。

<script>
int code = 1;
ServerMethod(code);
</script>

  这是由于页面没有完全加载完毕而调用的问题,不会报错,但是没有效果。

  相关技术介绍

  1. 本技术主要使用了asp.net的回调技术,ICallbackEventHandler

  2. 结合了反射原理

  具体就不点明了,各位大侠看看源码就懂了。

  源码下载

  http://www.boxcn.net/shared/86y259srcv


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3