c#后台写javascript前端调用

最近比较清闲,就来逛逛控件网,发现了一个非常好的类库,可惜没看到源代码,不过使用方式和dll类库倒是能下载到,先发来贴这里,用起来比较方便

针对的情况是c#后台代码写个函数,然后前端代码可以直接调用,确实蛮方便,增加了前后台的交互。

这种方式用c#+EasyUI+Ajax.dll可以很方便的从c#后台拉送数据EasyUI做HTML展现,Ajax.dll做数据传输的桥梁。

演示的DEMO就1个default页面:

<%@ Page Language="C#" AutoEventWireup="true" 
Codebehind="Default.aspx.cs" Inherits="DemoAjaxApp._Default" %>

<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, 
    Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        Namespace="System.Web.UI" TagPrefix="asp" %>

<!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>Ajax Demo</title>

    <script language="javascript" type="text/javascript">
             
        function CallTest()
        {
            var id=document.getElementById('txtClientId').value;
            Test(id);
        }
        function NameLength(obj)
        {
            var i=0;
            var newdiv = document.getElementById('EmpData');
            newdiv.innerHTML = "";
            if(obj == null)
            {    
                newdiv.innerHTML = "No Employee Found";
                return;
            }
            mytable = document.createElement("table");
            mytable.cellSpacing = "0px";
            mytable.style.border = "1px solid #000";
            mytablebody = document.createElement("tbody");
            mycurrent_row = document.createElement("tr");
            for(i=0;i<obj.Rows[0].Columns.length;i++)
            {
                mycurrent_cell = document.createElement("td");
                currenttext = document.createTextNode
                        (obj.Rows[0].Columns[i].Name);
                mycurrent_cell.appendChild(currenttext);
                mycurrent_cell.style.border = 
                        "1px solid #000";
                mycurrent_row.appendChild(mycurrent_cell);
            }    
            mytablebody.appendChild(mycurrent_row);    
            for(var j=0;j<obj.RowCount;j++)
            {
                var objRow = obj.Rows[j];
                mycurrent_row = document.createElement("tr");
                for(i=0;i<objRow.Columns.length;i++)
                {
                    mycurrent_cell = 
                        document.createElement("td");
                    if(objRow.Columns[i].Value != null)
                        currenttext = 
                        document.createTextNode
                        (objRow.Columns[i].Value 
                        + " ");
                    else
                        currenttext = 
                        document.createTextNode(" ");
                    mycurrent_cell.appendChild
                            (currenttext);
                    mycurrent_cell.style.border = 
                            "1px solid #000";
                    mycurrent_row.appendChild
                            (mycurrent_cell);
                }
                mytablebody.appendChild(mycurrent_row);
            }
            mytable.appendChild(mytablebody);
            newdiv.appendChild(mytable);
                            
        }
        function Error_Test(obj)
        {
            alert(obj.ErrMsg);
        }
        function CallTest1()
        {
            var x = new Array();
            x[0] = "Mehul";
            x[1] = "Thakkar";
            PassArrayObject(x);
        }
        function ReturnClassObject(obj)
        {
            alert(obj.Name);
        }
        function Error_PassArrayObject(obj)
        {
            alert(obj.ErrMsg);
        }
        function CallReturnEvenOdd() 
                {
                    var id = document.getElementById('txtNumber').value;
                    var msg = ReturnEvenOdd(id);
                    alert(msg);
                }
        function CallTest2()
        {
            var x = new Object();
            x.Name = "Mehul-Thakkar";
            x.Phone = 25460645;
            x.Email = "[email protected]";
            x.JoiningDate = "15-09-2010";
            PassClassObject(x);
        }
        function ReturnLength(obj)
        {
            alert(obj);
        }
        function Error_PassClassObject(obj)
        {
            alert(obj.ErrMsg);
                }

        function CallBack_ReturnArray(arrObj)
        {
            var Total=0;
            for(var i in arrObj)
                Total+=parseInt(arrObj[i],10);
                
            alert(Total);
        }
        function CallBack_ReturnStrArray(arrObj)
        {
            var str='';
            for(var i in arrObj)
                str+=arrObj[i]+"\n";
                
            alert(str);
        }
        function CallBack_ReturnObject(clsObj)
        {
            alert(clsObj.Email);
        }
            function CallBack_ReturnFArray(arrObj)
        {
            var Total=0;
            for(var i in arrObj)
            Total+=parseFloat(arrObj[i],10);
                
            alert(Total);
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
     <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <div>
            <div style="border: solid 1px yellow">
                Enter Emp No Here:
                <input type="text" id="txtClientId" />
                <a href="#" onclick="CallTest()">Retrieve Emp</a>
                <div id="EmpData">
                </div>
            </div>
            <br />
            <div style="border: solid 1px blue">
                Pass Array Object:
                <a href="#" onclick="CallTest1()">Click Here</a>
                <div id="Div1">
                </div>
            </div>
            <br />
            <div style="border: solid 1px green">
                Pass Class Object:
                <a href="#" onclick="CallTest2()">Click Here</a>
                <div id="Div2">
                </div>
            </div>
            <br />
            <div style="border: solid 1px orange">
                Return Array Object:
                <a href="#" onclick="ReturnArray()">Click Here</a>
                <div id="Div3">
                </div>
            </div>
            <br />
            <div style="border: solid 1px brown">
                Return String Array Object:
                <a href="#" onclick="ReturnStrArray()">Click Here</a>
                <div id="Div5">
                </div>
            </div>
            <br />
            <div style="border: solid 1px pink">
                Return Double Array Object:
                <a href="#" onclick="ReturnFArray()">Click Here</a>
                <div id="Div6">
                </div>
            </div>
            <br />
            <div style="border: solid 1px gray">
                Return Class Object:
                <a href="#" onclick="ReturnObject()">Click Here</a>
                <div id="Div4">
                </div>
            </div>
            <br />
            <div style="border: solid 1px silver">
                Synchronous Call using AJAX:
                <input type="text" id="txtNumber" />
                <a href="#" onclick="CallReturnEvenOdd()">Click Here</a>
                <div id="Div7">
                </div>
            </div>
            <br />
            <div style="border: solid 1px red">
            Access this textbox from Ajax dll
            <asp:TextBox runat="server" ID="txt"></asp:TextBox>
            <a href="#" onclick="ControlAccess()">Get Error</a>
            </div>
        </div>
       
        <asp:UpdatePanel runat="server" ID="UP1">
            <ContentTemplate>
                <asp:TextBox runat="server" ID="txt1">
                </asp:TextBox>
                <asp:Button runat="server" ID="b1" 
                  Text="click here" OnClick="b1_Click" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>

Default.CS文件如下:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;

namespace DemoAjaxApp
{
    public class Temp
    {
        string _name, _email;
        int _phone;

        public string Name { get { return _name; } set { _name = value; } }
        public int Phone { get { return _phone; } set { _phone = value; } }
        public string Email { get { return _email; } set { _email = value; } }

    }
    public partial class _Default : System.Web.UI.Page
    {
    [Ajax.AjaxMethod("Test", "NameLength", null, "Loading...")]
        public DataTable Test(string Id)
        {
            System.Data.SqlClient.SqlConnection con = 
            new System.Data.SqlClient.SqlConnection
        ("server=mehul;Database=master;User Id=sa;Password=");
            System.Data.SqlClient.SqlDataAdapter Adp = 
            new System.Data.SqlClient.SqlDataAdapter
        ("Select * from emp where no=" + Id, con);

            DataTable dt = new DataTable();
            try
            {
                Adp.Fill(dt);
                if (dt.Rows.Count > 0)
                    return dt;
                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        [Ajax.AjaxMethod("PassArrayObject", 
          "ReturnClassObject", null, "Loading...")]
        public Temp PassArrayObject(string[] str)
        {
            Temp t1 = new Temp();
            foreach (string st in str)
                t1.Name += st;

            return t1;
        }

        [Ajax.AjaxMethod("PassClassObject", "ReturnLength", null, "Loading...")]
        public int PassClassObject(Temp str)
        {
            return str.Name.Length;
        }

        [Ajax.AjaxMethod("ControlAccess", false, false, "Loading...")]
        public void ControlAccess(string str)
        {
            txt.Text = str;
        }

        [Ajax.AjaxMethod(false)]
        public string ReturnEvenOdd(int i)
        {
            if (i % 2 == 0)
                return "Number is Even";
            else
                return "Number is Odd";
        }

        [Ajax.AjaxMethod(null, true, false, "Loading...")]
        public int[] ReturnArray()
        {
            int[] i ={ 1, 2, 3, 4 };
            return i;
        }

        [Ajax.AjaxMethod]
        public string[] ReturnStrArray()
        {
            string[] str ={ "\\'1\\'", "2", "3", "4" };
            return str;
        }

        [Ajax.AjaxMethod(null, true, false, "Loading...")]
        public double[] ReturnFArray()
        {
            double[] i ={ 1.423, 2.543, 3.765, 4.65 };
            return i;
        }

        [Ajax.AjaxMethod(null, true, false, null)]
        public Temp ReturnObject()
        {
            Temp obj = new Temp();
            obj.Name = "hello";
            obj.Phone = 420840;
            obj.Email = "[email protected]";
            return obj;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Ajax.Utility.GenerateMethodScripts(this);
        }

        protected void b1_Click(object sender, EventArgs e)
        {
            txt1.Text = "hello";
        }
    }
}

 

简单介绍一下吧:

    /*
     * 使用Ajax.AjaxMethod类时,是有5个参数的
     * 1.第一个参数是你想客户端调用JS的名称,默认是函数名称
     * 2.第二个参数是JS调用成功后回调函数的名称默认命名为Callback_<你的函数名>
     * 3.第三个参数是JS调用后台后出现异常时回调函数,默认名称为Error_<你的函数名称>
     * 4.第四个参数是在调用后台代码等待过程中,显示的字符信息,默认是String.Empty
     * 5.第五个参数为是否时异步调用,确认你客户端调用js时是否为异步调用,默认是true(异步)
     */

这个也是从网站类库说明中翻译出来的,大概就这个意思!

确实蛮方便的,省去了ScriptManager注册一大堆乱七八糟的脚本什么的了。而且使用的也是异步调用,会送数据,使用IE调试了一下,发现其原理其实是创建了一个同名的ashx文件进行后台页面代码的调用。

c#后台写javascript前端调用_第1张图片

很明显的创建了一个文件并在后台调用了该文件

不多说了,直接上代码调一下就能看到其实现的原理了!

13:55:5

你可能感兴趣的:(JavaScript)