GridView右键菜单进行无刷新操作
朱乙的半亩田 http://blog.csdn.net/sq_zhuyi/archive/2009/02/27/3

 

 

 

 

 

 

 

 

default.aspx

 

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

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
http://www.w3.org/1999/xhtml">

   
   
   


   
       


           
               
               
                   
                   
                   
                   
               

               
               
           

       

       
   

 

default.aspx.cs

 

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;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["getinfo"] != null)
        {
            GetInfo();
            Response.End();
        }
        if (Request.QueryString["delete"] != null)
        {
            DeleteInfo();
            Response.End();
        }
        if (Request.QueryString["edit"] != null)
        {
            EditInfo();
            Response.End();
        }
        if (!IsPostBack)
        {
            CreateTable();

            DataTable dt = DB.GetTable("select * from test_users");
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }

    private void CreateTable()
    {
        string sql = "select [name] from sysobjects where objectproperty(object_id('test_users'),'istable') = 1";
        int c = DB.GetTable(sql).Rows.Count;
        if (c > 0) return;
        sql = @"create table test_users(
_id int identity(1,1) not null,
_name varchar(50) not null,
_sex varchar(4) not null,
_age int null,
_email varchar(100) null,
_address varchar(200) null)
go
insert into test_users(_name,_sex,_age,_email,_address)
select '刘备','男',32,'liubei@sanguo.com','朝阳公园' union
select '关羽','男',28,'guanyu@sanguo.com','中关村' union
select '张飞','男',27,'zhangfei@sanguo.com','八里庄西里' union
select '赵云','男',22,'zhaoyun@sanguo.com','东长安街' union
select '貂蝉','女',20,'diaochan@sanguo.com','避暑山庄'";
        DB.Execute(sql);
    }

    private void GetInfo()
    {
        int id = 0;
        if (!int.TryParse(Request.QueryString["id"], out id))
        {
            Response.Write("error");
            return;
        }
        string sql = "select * from test_users where _id=" + id.ToString();
        DataTable dt = DB.GetTable(sql);
        if (dt.Rows.Count == 0)
        {
            Response.Write("error");
            return;
        }
        DataRow row = dt.Rows[0];

        StringBuilder sb = new StringBuilder();
        sb.Append("

");
        sb.AppendFormat("
", row["_name"]);
        sb.AppendFormat("
", row["_sex"]);
        sb.AppendFormat("
", row["_age"]);
        sb.AppendFormat("
", row["_email"]);
        sb.AppendFormat("
", row["_address"]);
        sb.Append("
姓名:{0}
性别:{0}
年龄:{0}
邮件:{0}
地址:{0}
");

        Response.Write(sb.ToString());
    }

    private void DeleteInfo()
    {
        int id = 0;
        if (!int.TryParse(Request.QueryString["id"], out id))
        {
            Response.Write("error");
            return;
        }
        string sql = "delete from test_users where _id=" + id.ToString();
        DB.Execute(sql);
        Response.Write("true");
    }

    private void EditInfo()
    {
        int id = 0;
        if (!int.TryParse(Request.QueryString["id"], out id))
        {
            Response.Write("error");
            return;
        }
        string sql = "update test_users set _name='{1}',_sex='{2}',_age={3} where _id={0}";
        sql = String.Format(sql, id, Request["name"].Replace("'", ""), Request["sex"] == "男" ? "男" : "女", int.Parse(Request["age"]));
        DB.Execute(sql);
        Response.Write("true");
    }
}

 

DB.cs

 

using System;
using System.Data;
using System.Data.SqlClient;

public class DB
{
    public DB()
    {
       
    }

    public static SqlConnection SqlConn
    {
        get { return new SqlConnection("server=(local);database=tempdb;uid=sa;pwd=;"); }
    }

    public static DataTable GetTable(string sql)
    {
        using (SqlConnection conn = SqlConn)
        {
            SqlDataAdapter da = new SqlDataAdapter(sql, conn);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds.Tables[0];
        }
    }

    public static int Execute(string sql)
    {
        using (SqlConnection conn = SqlConn)
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            return cmd.ExecuteNonQuery();
        }
    }
}

 


default.js

 

function el(id){
    return document.getElementById(id);
}
window.onload = function(){
    el("GridView1").oncontextmenu = function(ev){
        showMenu(ev);
        return false;
    };
    document.onmousedown = function(){if(!over)hideMenu();};
};
var over = false;
var menu = null;
function showMenu(ev){
    ev = ev || window.event;
    hideMenu();
    var e = ev.srcElement || ev.target;
    if(e.tagName=="TH") return;
    var x = ev.pageX || ev.clientX + document.documentElement.scrollLeft;
    var y = ev.pageY || ev.clientY + document.documentElement.scrollTop;
    menu = document.createElement("DIV");
    menu.className = "menu";
    menu.style.left = x+4+"px";
    menu.style.top = y+"px";
    document.body.appendChild(menu);

    var id = e.parentNode.getElementsByTagName("td")[0].innerHTML;   
    e.parentNode.id = "tr_"+id;
   
    var s = "查看详细信息";
    s += "修改用户信息";
    s += "删除该条记录";
    s = s.replace(/{id}/g, id);
   
    menu.innerHTML = s;
    menu.onmouseover = function(){over=true;};
    menu.onmouseout = function(){over=false;};
}
function hideMenu(){
    if(menu){
        document.body.removeChild(menu);
        menu = null;
    }
}
function showInfo(id){
    hideMenu();
    shideBody();
   
    el("tit").innerHTML = "查看用户的详细信息";
    el("bod").innerHTML = "loading...";
    el("bot").innerHTML = "";
   
    var req = getReq();
    req.open("GET", "default.aspx?getinfo=1&id="+id, true);
    req.onreadystatechange = function(){
        if(req.readyState==4){
            el("bod").innerHTML = req.responseText;
        }
    };
    req.send(null);
}
function editInfo(id){
    hideMenu();
    shideBody();
   
    el("tit").innerHTML = "编辑用户信息";
    el("bod").innerHTML = "loading...";
    el("bot").innerHTML = " ";
    var tds = el("tr_"+id).getElementsByTagName("td");
    var boy = tds[2].innerHTML == "男";
    var s = "

";
    s += "";
    s += "";
    s += "";
    s += "
姓名
性别
年龄
";
    el("bod").innerHTML = s;
}
function deleteInfo(id){
    hideMenu();
    if(!confirm("确定要删除该记录吗?"))return;
   
    removeRow(el("tr_"+id));
   
    var req = getReq();
    req.open("GET", "default.aspx?delete=1&id="+id, true);
    req.onreadystatechange = function(){};
    req.send(null);
}
function doEdit(id){
    var puts = el("bod").getElementsByTagName("input");
    if(isNaN(puts[3].value)){
        puts[3].select();return;
    }
    var tds = el("tr_"+id).getElementsByTagName("td");
    tds[1].innerHTML = puts[0].value;
    tds[2].innerHTML = puts[1].checked?"男":"女";
    tds[3].innerHTML = puts[3].value;
   
    var data = "name="+ escape(tds[1].innerHTML);
    data += "&sex="+ escape(tds[2].innerHTML);
    data += "&age="+ escape(tds[3].innerHTML);
   
    var req = getReq();
    req.open("POST", "default.aspx?edit=1&id="+id, true);
    req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    req.onreadystatechange = function(){};
    req.send(data);
   
    cancelShide();
}

var shield;
function shideBody()
{
    shield = document.createElement("DIV");
    shield.id = "shield";
    shield.style.position = "absolute";
    shield.style.left = "0px";
    shield.style.top = "0px";
    shield.style.width = "100%";
    shield.style.height = document.documentElement.scrollHeight+"px";
    shield.style.background = "#333333";
    shield.style.textAlign = "center";
    shield.style.zIndex = "10";
    shield.style.filter = "alpha(opacity=0)";
    shield.style.opacity = 0;
    document.body.appendChild(shield);
   
    this.setOpacity = function(obj,opacity){
    if(opacity>=1)opacity=opacity/100;
    try{ obj.style.opacity=opacity; }catch(e){}
    try{
        if(obj.filters.length>0 && obj.filters("alpha")){
            obj.filters("alpha").opacity=opacity*150;
        }else{
            obj.style.filter="alpha(opacity=\""+(opacity*150)+"\")";
        }
    }catch(e){}
    }
    var c = 0;
    this.doAlpha = function(){
    if (++c > 20){clearInterval(ad);return 0;}
    setOpacity(shield,c);
    }
    var ad = setInterval("doAlpha()",1);

    el("divh").style.display = "";
    el("divh").style.marginTop = -75+document.documentElement.scrollTop + "px";
}
function cancelShide()
{
    if(el("divh"))
    {
        el("divh").style.display = "none";
    }
    if(shield)
    {
        document.body.removeChild(shield);
        shield = null;
    }
}

function getReq()
{
    var oHttpReq = null;
   
    if(window.ActiveXObject)
        oHttpReq = new ActiveXObject("MSXML2.XMLHTTP");
    else if(window.createRequest)
        oHttpReq = window.createRequest();
    else
        oHttpReq = new XMLHttpRequest();
       
    return oHttpReq;
}

function removeRow(e)
{
    e.style.backgroundColor = "#ff0000";
    setTimeout(function(){e.style.backgroundColor = "#ffcccc";},100);
    setTimeout(function(){e.style.backgroundColor = "MistyRose";},300);
    setTimeout(function(){e.style.display = "none";},450);

 

CIO之家 www.ciozj.com 公众号:imciow
关联的文档
也许您喜欢