一个Ajax.NET的查询实例


因为项目中只能用.net 1.1,所以atlas是用不了了,只能玩玩AjaxProfession.net, 下面是一个查询的案例。 在页面上放置一个DataGrid1,各种查询结果均放入其中,在client端的JS中将SQL语句传给server端的方法,执行一个查询,并可以控制双击行是否展开一个新的查询。

可将DataGrid1的内容导出到excel中、模拟gmail的Ajax的loading运用

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
namespace eol
{
    /**//// <summary>
    /// index 的摘要描述。
    /// </summary>
    public class index : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.TextBox TextBox1;
        protected WebControlLibrary.InputCalendar startTime;
        protected WebControlLibrary.InputCalendar endTime;
        protected WebControlLibrary.InputCalendar pStartTime;
        protected WebControlLibrary.InputCalendar pEndTime;
        protected System.Data.SqlClient.SqlConnection Conn=new SqlConnection();
        protected System.Web.UI.WebControls.TextBox eformsn;
        protected System.Web.UI.WebControls.Label Label1;
        protected System.Web.UI.WebControls.DataGrid DataGrid1=new DataGrid();
        protected System.Web.UI.WebControls.Button Button2;
        protected System.Web.UI.HtmlControls.HtmlInputText applicant;
        public string toExcel;
   
        private void Page_Load(object sender, System.EventArgs e)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(eol.index));
        }

        public DataSet DB(string dataName, string sqlCmd)
        {
            string connStr="server=172.16.0.120;uid=msikdb;pwd=dbmsik;database="+dataName;
            Conn.ConnectionString=connStr;
            try
            {
                Conn.Open();
            }
            catch(Exception ex)
            {
                Conn.Close();
                Response.Write(ex.Message);
            }
            SqlCommand cmd=new SqlCommand(sqlCmd, Conn);
            SqlDataAdapter da=new SqlDataAdapter();
            da.SelectCommand=cmd;
            DataSet ds = new DataSet();
            da.Fill(ds);
            Conn.Close();
            return ds;
        }

        Web Form 设计工具产生的程式码#region Web Form 设计工具产生的程式码
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: 此为 ASP.NET Web Form 设计工具所需的呼叫。
            //
            InitializeComponent();
            base.OnInit(e);
        }
       
        /**//// <summary>
        /// 此为设计工具支援所必须的方法 - 请勿使用程式码编辑器修改
        /// 这个方法的内容。
        /// </summary>
        private void InitializeComponent()
        {   
            this.Conn = new System.Data.SqlClient.SqlConnection();
            this.Button2.Click += new System.EventHandler(this.Button2_Click);
            this.DataGrid1.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.getPageIndexStyle);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion


        private void getPageIndexStyle(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
           
            if(e.Item.ItemType == ListItemType.Pager)
            {
                e.Item.Cells[0].Text="Total Row:"+this.DataGrid1.Items.Count.ToString();
            }
        }
       
        [AjaxPro.AjaxMethod]
        public string AjaxData(string sSql, bool clientEvent)
        {
            if (clientEvent)
            {
                DataGrid1.ItemDataBound+=new DataGridItemEventHandler(DataGrid1_ItemDataBound);
            }
//            DataGrid1.AllowPaging=true;
//            DataGrid1.PagerStyle.Position=PagerPosition.Top;
//            DataGrid1.PagerStyle.Mode=PagerMode.NumericPages;
//            DataGrid1.ItemCreated+=new DataGridItemEventHandler(getPageIndexStyle);
            DataGrid1.DataSource=DB("query",sSql);
            DataGrid1.HeaderStyle.BackColor=System.Drawing.Color.Blue;
            DataGrid1.Width=Unit.Percentage(100);
            DataGrid1.HeaderStyle.ForeColor=System.Drawing.Color.White;
            DataGrid1.DataBind();
           
           
            System.Text.StringBuilder sb=new System.Text.StringBuilder();
            System.IO.StringWriter sw=new System.IO.StringWriter(sb);
            System.Web.UI.HtmlTextWriter htw=new HtmlTextWriter(sw);
            this.DataGrid1.RenderControl(htw);
            string s=sb.ToString().Replace(" 上午 12:00:00", "");
            this.toExcel=s;
            Session["txtExcel"]=s;
            return s;
        }
       
        public void setToExcel()
        {
            //下面这行很重要,attachment 参数表示作为附件下载,您可以改成online在线打开
            //filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc    .xls    .txt  .htm  
            Response.AppendHeader("Content-Disposition","attachment;filename=EOL_"+eformsn.Text+".xls");
            Response.ContentEncoding=System.Text.Encoding.GetEncoding("big5"); 
            //Response.ContentType指定文件类型 可以为application/ms-excel,application/ms-word ,application/ms-txt,application/ms-html或其他浏览器可直接支持文档 
            Response.ContentType = "application/ms-excel";

            Response.Write(this.toExcel);
            Response.Write(Session["txtExcel"]);
            Session.Abandon();
            Response.End();
        }

        private void Button2_Click(object sender, System.EventArgs e)
        {
            setToExcel();
        }

        private void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            ListItemType itemtype=(ListItemType)e.Item.ItemType;
            if (itemtype!=ListItemType.Header && itemtype!=ListItemType.Footer && itemtype!=ListItemType.Separator)
            {
                e.Item.Attributes.Add("ondblclick", "showDetail("+e.Item.Cells[1].Text+");");
                e.Item.Attributes.Add("onmouseover","this.className='mouseOn'");
                e.Item.Attributes.Add("onmouseout", "this.className=''");
            }
        }

    }
}
Client端的js:
<script language="javascript">       
var obj=document.all;
var frm=document.forms[0];
var box=document.getElementById("detail");
var list=document.getElementById("datagrid");

if(typeof ASP == "undefined") ASP={};
ASP.LoadingDemo_class = function() {};
Object.extend(ASP.LoadingDemo_class.prototype, Object.extend(new AjaxPro.AjaxClass(), {
    LongOperation: function() {
        return this.invoke("LongOperation", {}, this.LongOperation.getArguments().slice(0));
    },
    url: '/ajaxpro/ASP.LoadingDemo,App_Web_t_mu_tej.ashx'
}));
ASP.LoadingDemo = new ASP.LoadingDemo_class();

var c = 0;
AjaxPro.onLoading = function(b) {
    c++;
    window.status = c;
    var l = document.getElementById("loadinfo");
    l.style.visibility = b ? "visible" : "hidden";
       l.style.right=0;
    l.style.pixelTop=document.body.scrollTop;
}

function showDetail(n) {
    c = 0;
    ASP.LoadingDemo.LongOperation(new Function('getEolByeFormsn('+n+')'));
}

function getDataGrid(sql,Event)
{
    if(list.style.display=='none')
    {
        list.style.display='';
    }
    box.style.display=='' ? box.style.display='none':void(0);
    var p=eol.index.AjaxData(sql, Event).value;
    list.innerHTML=p;
}

function getEolByeFormsn(n)
{
    if (box.style.display=="none")
    {
        box.style.display="";
        box.innerHTML="<div id='toolbar'><div id='btnGoback' onclick='goBack()'><img src=http://172.16.0.134/webflow/images/cch.gif>GO BACK</div></div>"
    }
    list.style.display="none";
    var p=eol.index.AjaxData("select * from msi_eol_list_line t where eformsn="+n, false).value;
    box.innerHTML+=p;
}

window.onload=function ()
{
    box.style.display="none";
    list.style.display="none";
    document.getElementById("btnQuery").onclick=whenQuery;
    document.getElementById("btnToexcel").style.visibility="hidden";
    document.getElementById("btnHelp").onclick=getHelp;
}
function goBack()
{
    box.style.display='none';
    list.style.display='';
}
function whenQuery()
{
    var type=document.getElementById("types");
    var err=time=param='';
    var sql="select distinct (select Count(eformsn) from query.dbo.msi_eol_list_line where eformsn=w.eformsn) Line, w.* from (select eFormsn, Cast(Apply_Date as datetime) as ApplyDate, Applicant, LOB, Cast(p_date as datetime) as PendingDate, 'process' as Status from webflow.dbo.tb_326_1 union select eformsn, Cast(apply_date as datetime), applicant, lob, Cast(p_date as datetime), 'over' as Status from webflowdata.dbo.tb_326_1 where flowendstatus='E') w inner join query.dbo.msi_eol_list_line as e on w.eformsn=e.eformsn where (w.eformsn=e.eformsn) ";
    switch (type.value)
    {
        case "eformsn":
            if (frm.eformsn.value!='')
            {
                param="and e.eformsn='"+frm.eformsn.value+"'";
            }else{
                err="请输入申请单号.!"
            }
            break;
        case "applytime":
            if (frm.startTime.value=='' && frm.endTime.value=='')
            {
                err="请输入申请起止时间";
            }
            break;
        case "applicant":
            if (frm.applicant.value!="")
            {
                param+="and e.applicant='"+frm.applicant.value+"' order by w.ApplyDate";
            }else{
                err='请输入申请者中文名';
            }
            break;
        case "lob":
            if (frm.lob.value!="")
            {
                param="and w.lob='"+frm.lob.value+"'";           
            }else{
                err="请输入LOB";
            }
            break;
        case "pendingtime":
            if (frm.pStartTime.value!="" && frm.pEndTime.value!=""){
                param=" and w.PendingDate between cast('"+frm.pStartTime.value+"' as datetime) and cast('"+frm.pEndTime.value+"' as datetime) order by w.PendingDate";
            }else{
                err="请输入Pending Time";
            }
            break;
        case "model":
            if (frm.model.value!=''){
                frm.startTime.value=frm.endTime.value='';
                sql='';
                param="select distinct (select count(model) from query.dbo.msi_eol_list_line where model=e.model) Total, eFormsn, Model, Applicant, LOB, Cast(Creation_date as datetime) as ApplyDate, Cast(pending_date as datetime) as PendingDate, (select Status from (select eFormsn, 'process' as Status from webflow.dbo.tb_326_1 union select eformsn, 'over' as Status from webflowdata.dbo.tb_326_1 where flowendstatus='E') as w where w.eformsn=e.eformsn) as Status from query.dbo.msi_eol_list_line as e where e.model='"+frm.model.value+"' group by Model, Applicant, LOB, Creation_date, Pending_Date, eformsn";
            }else{
                err="请输入Model";
            }
            break;
    }
    if (err=='')
    {
        if (frm.startTime.value!='' && frm.endTime.value!='')
        {
            time="and ApplyDate between Cast('"+frm.startTime.value+"' as datetime) and Cast('"+frm.endTime.value+"' as datetime) ";
        }

        sql+=time+param;
        //document.write(sql);
        c = 0;
        ASP.LoadingDemo.LongOperation(new Function('getDataGrid("'+sql+'",true)'));
    }else{
        alert(err);
    }
}

var oPopup = window.createPopup();
function getHelp()
{
  var oPopupBody = oPopup.document.body;
  var lefter = screen.width-150;
  var topper = document.body.scrollTop;
  oPopupBody.innerHTML = helpbox.innerHTML;
  oPopup.show(lefter, topper, 280, document.body.offsetHeight, document.body);
  document.body.onmouseup = new Function("oPopup.hide();");
}
</script>

本文作者:



相关阅读:
CSS教程:li和ul标签用法举例
javascript getElementByTagName的使用
vim 计算搜寻关键字数量
分析Ora-01555(snapshot_too_old)错误
在一个页面做两种超链接的CSS样式
jsp进度条
第13课:上传网页
Ubuntu Linux下如何用源码文件安装软件
js实现图片加载时候逐渐出现的杂色效果
vbs更改3389远程桌面端口的脚本
初学js插入节点appendChild insertBefore使用方法
Linux下用GTK和socket实现简单的聊天室
CSS Tricks精选出的一些精灵图片
在PHP与DB2 9中使用Ajax:Xajax
快速导航

Copyright © 2016 phpStudy | 皖ICP备18014864号-4