1.将客户端转到新的URL
Response.Redirect("goodsmanage.aspx");
Response.Write("<script>alert('保存成功!!');window.location.href='OutList.aspx';</script>");
------------------------------------------------------
------------------------------------------------------
2.获取HTTP查询字符串变量
如:http://localhost:1129/WMS/goodsmodify.aspx?gid=3
Request.QueryString ["gid"].ToString ()
或Request.Params["gid"].ToString ()
或Request["nid"].ToString()
------------------------------------------------------
------------------------------------------------------
3.获取向当前页传输的控件(必须以此属性PostBackUrl进行页面跳转)
TextBox pp_Textbox1 = (TextBox)PreviousPage.FindControl("Textbox1");
------------------------------------------------------
------------------------------------------------------
4.Html的含义
<br/> 换行
空格
<p> 分段
<hn> 标题,其中n为1~6
<marquee> 移动的文本 <marquee direction='up' onmouseover=this.stop() onmouseout=this.start() scrollAmount=3 scrollDelay=100>1111</marquee>
<a> 超链接
<hr> 水平线标记 <hr size=2 width=1000 align=center>
<b> 粗体
<i> 斜体
< <
> >
<sup> 如2的3次幂的3的位置,即上标
<sub> 下标
& &
↑ ↑
← ←
→ →
↓ ↓
------------------------------------------------------
------------------------------------------------------
5.ASP.net页面的启动顺序
(1)PreInit:表示页面初始化前的那一刻
(2)Init
(3)InitComplete:表示页面完成了初始化
(4)PreLoad:表示页面加载到内存前的那一刻
(5)Load
(6)LoadComplete:表示页面完全加载到内存中
(7)PreRender
(8)PreRenderComplete:表示页面显示在浏览器中之前的那一刻
(9)Unload
------------------------------------------------------
------------------------------------------------------
6.含有master页面的启动顺序
(1)master页面子控件初始化
(2)内容页面子控件初始化
(3)master页面初始化
(4)内容页面初始化
(5)内容页面的加载
(6)master页面的加载
(7)master页面子控件的加载
(8)内容页面子控件的加载
------------------------------------------------------
------------------------------------------------------
7.获取当前正在执行的服务器应用程序的根目录的路径
Request.PhysicalApplicationPath
------------------------------------------------------
------------------------------------------------------
8.点击Button弹出对话框
<asp:Button ID="Button3" runat="server" Text="Button" OnClientClick="return confirm( '你确定要添加吗? ');" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return alert( '添加成功! ');" />
或
在Page_Load中添加
this.Button1.Attributes.Add("onclick", "return confirm('确实要删除数据吗?');");
this.btnDelete.Attributes ["onclick"]="javascript:return confirm('您确认要删除吗?');";
------------------------------------------------------
------------------------------------------------------
9.点击GridView或DetailView的删除按钮时弹出确认对话框
点击控件的“编辑列”或“编辑字段”,在“选定的字段”中选择删除按钮,
点击右下角的“将此字段转换为TemplateField”,之后在程序中加入
<asp:LinkButton ID="LinkButton3" runat="server"
CommandName="Delete" Text="删除" OnClientClick="return confirm('您确认要删除吗?')" >
</asp:LinkButton>
------------------------------------------------------
------------------------------------------------------
10.在页面的任意地方弹出提示对话框
Response.Write("<script>alert('对话框上提示的内容')</script>");
------------------------------------------------------
------------------------------------------------------
11.在URL中写入参数、以GridView为例
在字段中添加HyperlinkField控件,
在属性窗口中的DataNavigateUrlFields中添加CategoryID
在DataNavigateUrlFotmatString中添加Default2.aspx?Category={0}
择导航后的链接为:http://localhost:1510/WebSite2/Default2.aspx?Category=2
------------------------------------------------------
------------------------------------------------------
12.Form身份认证配置文件,匿名用户登录时转到Formslogin.aspx页
<system.web>
<authentication mode="Forms">
<forms name=".ASPXUSERDEMO" loginUrl="Formslogin.aspx" protection="All" timeout="60"/>
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
name:终端用户进行身份验证后发送给他们的cookie的名字,默认时,这个cookie为.ASPXAYTH。注意,如果一个服务器有很多应用的话,要给cookie其不同的名字
loginUrl:指定一个用于登陆的页面
timeout:Cookie的存活时间默认值是30分钟,此过期时间为此登录验证的过期时间
protection:Cookie被保存的方式
后台代码:
if (验证成功)
{
if (FormsAuthentication.GetRedirectUrl(dataReader["userID"].ToString(), false).ToLower().EndsWith("default.aspx"))
{
FormsAuthentication.SetAuthCookie(dataReader["userID"].ToString(), false);
Response.Redirect("MainWeb.aspx");
}
else
{
FormsAuthentication.RedirectFromLoginPage(dataReader["userID"].ToString(), false);
}
}
当注销时需要加:
FormsAuthentication.SignOut();
------------------------------------------------------
------------------------------------------------------
13.设置程序中Session的过期时间
Global.asax文件中:
void Session_Start(object sender, EventArgs e)
{
//在新会话启动时运行的代码
Session.Timeout = 100;
}
------------------------------------------------------
------------------------------------------------------
14.获取有关发出页请求的用户信息
User
if (!User.Identity.IsAuthenticated)
Wizard1.ActiveStepIndex = 0;
------------------------------------------------------
------------------------------------------------------
15.成员管理和角色管理
成员管理基于membership、menbershipUser两个类
角色管理基于role类
------------------------------------------------------
------------------------------------------------------
16.将GridView中行中列的值为需要的值时,背景改变
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int i = int.Parse ( DataBinder.Eval(e.Row.DataItem, "CategoryID").ToString ());
if (i == 1)
{
e.Row.BackColor = System.Drawing.Color.Red;
}
}
}
------------------------------------------------------
------------------------------------------------------
17.#为数据绑定的标志
DataSource='<%# GetData() %>'
<%#ComputeSeniorityLevel(DateTime.Now - CType(Eval("HireDate"), DateTime))%>
<a href="manager/downloadfile.aspx?filepath=<%# Eval("filepath", "{0}") %>&filename=<%# Eval("filename", "{0}") %>&fid=<%# Eval("fid", "{0}") %>"></a>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# Eval("PictureURL", @"ProductImages\thumb_{0}") %>'
AlternateText='<%# Eval("Description") %>' PostBackUrl='<%# Eval("ProductID", "ShopItem.aspx?ProductID={0}") %>'>
</asp:ImageButton>
或
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# Eval("PictureURL", "~\ProductImages\thumb_{0}") %>'
AlternateText='<%# Eval("Description") %>' PostBackUrl='<%# Eval("ProductID", "ShopItem.aspx?ProductID={0}") %>'>
</asp:ImageButton>
<a href="VisitMenuManage.aspx?id=<%# Eval("userID") %>">权限</a>
<a href='<%# string.Format("~/Items.aspx?itemId={0}&productId={1}&categoryId={2}", Eval("ItemId"), Eval("ProductId"), Eval("CategoryId")) %>'></a>
绑定中的逻辑判断:
<asp:Label ID="Label1" runat="server" Text='<%# Eval("userStyle").ToString()=="1"?"超级管理员":"普通管理员" %>'></asp:Label>
------------------------------------------------------
------------------------------------------------------
18.在GridView中添加合计行
将GridView的ShowFooter属性设为true
private decimal priceTotal = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
priceTotal += decimal.Parse(DataBinder.Eval(e.Row.DataItem, "UnitPrice").ToString());
}
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].Text = "Totals:";
e.Row.Cells[5].Text = priceTotal.ToString("c");
e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Center;
e.Row.Cells[5].HorizontalAlign = HorizontalAlign.Center;
}
}
------------------------------------------------------
------------------------------------------------------
19.将URL转换为在请求客户端可用的URL
ResolveUrl("~/DisplayingImages/Images/Sunset.jpg")
------------------------------------------------------
------------------------------------------------------
20.获取浏览器的语言
CultureInfo.CurrentCulture.Name
------------------------------------------------------
------------------------------------------------------
21.返回与WEB服务器上的指定虚拟路径相对应的物理文件路径
Server.MapPath(path)
------------------------------------------------------
------------------------------------------------------
22.删除menu的箭头
StaticEnableDefaultPopOutImage属性设置为false
------------------------------------------------------
------------------------------------------------------
23.点击按钮执行js程序
在Page_Load中添加
btnRemove.Attributes["onclick"] = "exchange(0);return false;";
其中exchange(dest)为js程序
或
txtStartTime.Attributes.Add("onclick", "turnDatePicker();");
其中turnDatePicker()为js程序
或
this.Linkbutton1.Attributes.Add("onclick", "AddDetailClick('"+strTEST+"')");
其中strTEST为后台向前台传递的变量,AddDetailClick()为js程序
------------------------------------------------------
------------------------------------------------------
24.验证页面是否成功
if (!IsValid)
return;
------------------------------------------------------
------------------------------------------------------
25.点击Button弹出新的窗体
在Page_Load中添加
Button1.Attributes.Add("onclick", "window.open('Default.aspx?')");
或
<a href="Default.aspx" target="_blank">点击</a>
target="_blank"是重点。
------------------------------------------------------
------------------------------------------------------
26.点击Gridview中的Bttton弹出新窗体,并传参数
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string s = e.Row.Cells[0].Text;
string updateUrl = string.Format("javascript:window.open('Default2.aspx?uid={0}');", s);
e.Row.Cells[4].Attributes.Add("onclick", updateUrl);
}
}
------------------------------------------------------
------------------------------------------------------
27.关闭子窗体并刷新父窗体数据
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("<Script>window.opener.opener= null;window.opener.location.replace(window.opener.location.href);window.close();</Script>");
或
Response.Write("<Script>window.opener.opener= null;window.opener.location.replace(window.opener.location.href);</Script>");
或
Response.Write("<script>window.opener.location='Default.aspx'</script>");
其中Default.aspx为要刷新的页面
}
------------------------------------------------------
------------------------------------------------------
28.获取当前请求的虚拟路径
Request.CurrentExecutionFilePath
------------------------------------------------------
------------------------------------------------------
29.设置焦点
TextBox4.Focus()
Page.SetFocus(TextBox1)
------------------------------------------------------
------------------------------------------------------
30.文件夹访问权限web.config
<system.web>
<authorization>
<deny users="*" />
</authorization>
</system.web>
<system.web>
<authorization>
<allow roles="FanClubMember" />
<deny users="*" />
</authorization>
</system.web>
<location path="Admin.aspx">
<system.web>
<authorization>
<allow roles="Reporter,Administrator,Owner,Manager" />
</authorization>
</system.web>
</location>
------------------------------------------------------
------------------------------------------------------
31.在弹出对话框的同时保持页面的显示
【原理】
在页面上放置一隐藏控件,并在页面最后放上一段脚本代码,脚本代码检测隐藏控件的value是否为空,若不为空则弹出对话框显示信息,否则什么也不做。
后台代码在需要的时候修改隐藏控件的value,这样当页面传到用户那时,最后的脚本代码将执行并弹出对话框。
【注意事项】
1.隐藏控件必须是HTML控件,否则javascript无法找到。
2.后台代码要修改隐藏控件的值,隐藏控件自然得加上runat=”server” 标记。
3.在弹出对话框后,记得把隐藏控件的value置空,否则刷新的时候又会弹出来了。
4.脚本代码一定得放在隐藏控件的后面,否则同样找不到。
【实现】
<body>
<form id="Form1" method="post" runat="server">
<asp:TextBox ID="manuInput" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="对话框" OnClick="Button1_Click"></asp:Button>
<input id="passTxt" type="hidden" runat="server"></form>
<script language="javascript">
if(document.all("passTxt").value!="")
{
alert(document.all("passTxt").value);
document.all("passTxt").value="";//这句可不能忘了哟!
}
</script>
</body>
后台代码(只列出Button1的响应事件)
protected void Button1_Click(object sender, EventArgs e)
{
passTxt.Value = manuInput.Text;
}
或动态添加脚本
protected void Button1_Click(object sender, EventArgs e)
{
string msg = "sssssss";
this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script language='javascript'>alert('" + msg.ToString() + "');</script>");
}
或在页面上写脚本
<head>
<title>ClientScriptManager Example</title>
<script language =javascript >
function DoClick()
{
if(document.all ("Message").value=="")
{
alert ('zzzzz');
}
}
</script>
</head>
<body>
<form id="Form1"
runat="server">
<input type="text" id="Message" /> <input type="button" value="ClickMe" onclick="DoClick()" />
</form>
</body>
------------------------------------------------------
------------------------------------------------------
32.在后台代码中使用HTML控件,则需添加runat="server"
<div id="searchResultDiv" runat=server visible=false><div>
protected void btnSearch_Click(object sender, EventArgs e)
{
this.searchResultDiv.Visible = true;
}
------------------------------------------------------
------------------------------------------------------
33.后退操作
<a href="#" onclick="history.go(-1);">返回</a>
<input id="Button2" type="button" value="button" onclick="history.go(-1);" />
------------------------------------------------------
------------------------------------------------------
34.后台代码与前台显示结合
当前路径:<%= currPath %>
目录数:<%= folderNum %>
文件数:<%= fileNum %>
其中currPath、folderNum、fileNum为后台代码的字段,为protected类型就行。
------------------------------------------------------
------------------------------------------------------
35.数据加密
一次加密:
public static string EncryptOne(string strPsswd)
{
strPsswd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strPsswd, "MD5");
return strPsswd;
}
n次加密:
public static string EncryptM(int n, string strPsswd)
{
for (int i = 1; i <= n; i++)
{
strPsswd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strPsswd, "MD5");
}
return strPsswd;
}
------------------------------------------------------
------------------------------------------------------
36.文本框失去焦点时文本框显示灰色文字的提示
input(text)文本输入框如下:
<form action="" method="post" name="form">
<input type="text" style="color:#999" name="name" value="这是提示文字" onfocus="this.style.color='#000'; if(this.value=='这是提示文字') {
this.value='' }"
onblur="if(this.value=='') { this.value='这是提示文字';this.style.color='#999' }"/>
</form>
TextBox如下:
<script type="text/javascript" language="javascript">
function onChangeValue()
{
var obj = document.getElementById("txtSchoolName");
if(obj.value=="请输入学校名称")
{
obj.value="";
obj.style.color="Black";
}
}
function offChangeValue()
{
var obj = document.getElementById("txtSchoolName");
if(obj.value=="")
{
obj.value="请输入学校名称";
obj.style.color="Gray";
}
}
</script>
<asp:TextBox ID="txtSchoolName" ForeColor="gray" onclick="onChangeValue()" onblur="offChangeValue()" runat="server">请输入学校名称</asp:TextBox>
------------------------------------------------------
------------------------------------------------------
37.页面底端有button(服务器控件),点击buton后页面仍旧保持在底端
<%@ Page Language="C#" .... MaintainScrollPositionOnPostback="true"%>
------------------------------------------------------
------------------------------------------------------
38.弹出一个对话框提示是否“操作成功”后跳转到某一个页面
Response.Write("<script>alert('删除成功!');window.location.href ='www.cnblogs.com'</script>");
------------------------------------------------------
------------------------------------------------------
31.在asp.net中..与~的区别
~/表示根目录,在服务器控件中指定路径时,可以使用该运算符
../表示上级目录
/标示根路径,不是服务器控件使用
------------------------------------------------------
------------------------------------------------------
32.当鼠标放在gridview某一行某列时,提示列名
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Attributes.Add("onmouseover", "this.style.cursor='hand';this.title='这是用户名';");
e.Row.Cells[1].Attributes.Add("onmouseover", "this.style.cursor='hand';this.title='这是添加的时间';");
}
}
------------------------------------------------------
------------------------------------------------------
33.一个页面有多个按钮和多个文本框,敲回车时提交哪一个按钮
服务器控件:
<form runat="server" defaultbutton="button1">
JS控制:
<script language="javascript">
document.onkeydown=function()
{
if(event.keyCode == 13)
{
alert("回车");
document.getElementById("btn").click();
return false;
}
}
</script>
------------------------------------------------------
------------------------------------------------------
34.取得GridView单元格的值
非模板列:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string myDate = GridView1.SelectedRow.Cells[0].Text;
}
摸板列:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="ID" Visible="False">
<ItemTemplate>
<asp:Label ID="musicID" runat="server" Text='<%#Eval("musicID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" HeaderText="下载" SelectText="下载" />
</Columns>
</asp:GridView>
注意:<asp:Label ID="musicID" runat="server" Text='<%#Eval("musicID")%>'></asp:Label>可以取到值
<asp:Label ID="musicID" runat="server"><%#Eval("musicID")%></asp:Label>取不到值
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string myDate = ((Label)GridView1.SelectedRow.Cells[0].FindControl("musicID")).Text;
}
------------------------------------------------------
------------------------------------------------------
35.后台向前台传递参数
<script language="javascript">
function Test(s)
{
alert (s);
}
</script>
protected void Button1_Click(object sender, EventArgs e)
{
string s = this.TextBox1.Text;
Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "<script>Test('" + s + "');</script>");
}
------------------------------------------------------
------------------------------------------------------
36.点击按钮弹出新窗体,并且传参数,并且解决参数中中文乱码问题
老窗体:
<script language="javascript">
function Test()
{
var a= encodeURI('111.aspx?id='+document.getElementById ("TextBox1").value);
window.open (a);
}
</script>
protected void Page_Load(object sender, EventArgs e)
{
Button1.Attributes.Add("onclick", "Test();");
}
新窗体:
protected void Page_Load(object sender, EventArgs e)
{
this.TextBox1.Text = Request.QueryString["id"].ToString();
}
------------------------------------------------------
------------------------------------------------------
37.使超级链接没有下划线
<style>
a
{
text-decoration: none;
}
a:hover
{
text-decoration: underline;
}
</style>
------------------------------------------------------
------------------------------------------------------
38.获取远程客户端的IP主机地址
Request.UserHostAddress
------------------------------------------------------
------------------------------------------------------
31.强制某个页面元素在页面上某个位置
<asp:TextBox ID="TextBox1" runat="server" style="bottom:30px; left:30px;position: absolute;"></asp:TextBox>
------------------------------------------------------
------------------------------------------------------
32.页面上点击鼠标左右键和回车键触发事件
<script language="javascript">
document.onmouseup = show;
document.onkeydown = show;
function show()
{
if (window.event.button == 1)
{
alert("左");
}
if (window.event.button == 2)
{
alert("右");
}
if(event.keyCode ==13)
{
alert ("回车");
}
}
</script>
------------------------------------------------------
------------------------------------------------------
33.写入与获取Cookie
写入Cookies:
Response.Cookies["k1"].Value = "k1Value";
Response.Cookies["k2"]["k2-1"] = "k2-1Value";
Response.Cookies.Add(new HttpCookie("k3", "k3Value"));
读取Cookies:
Request["k1"];
Request.Cookies["k1"].Value;
Request.Cookies["k2"]["k2-1"];
Request.Cookies.Get(0).Value;
------------------------------------------------------
------------------------------------------------------
34.设置Cookie的过期时间
Response.Cookies["UserID"].Expires = new DateTime(2020, 1, 1);
------------------------------------------------------
------------------------------------------------------
35.打开模态对话框,并传递变量
父窗口传递变量:
window.showModalDialog("../SM/Setup.aspx",window,"dialogWidth:500px;dialogHeight=140px;status:no");
其中window为传递的变量
子窗口接收变量:var parwin = window.dialogArguments;
------------------------------------------------------
------------------------------------------------------
36.window.open例子
window.open('111.aspx','_blank'); //在新窗口中打开
------------------------------------------------------
------------------------------------------------------
37.出错时会自动将页面跳转到当前站点根目录下面的DisplayError.aspx页面
<system.web>
<customErrors mode="On" defaultRedirect="~/DisplayError.aspx"></customErrors>
</system.web>
------------------------------------------------------
------------------------------------------------------
38.CSS样式
.progress //类名为progress
{
border: 1px solid #dfdfdf;
padding: 4px;
height: 2.6em;
}
.progress img //progress中的img
{
float: left;
padding: 0 10px 0 0;
}
.progress div //progress中的div
{
line-height: 32px;
width: 100px;
}
------------------------------------------------------
------------------------------------------------------
39.HTML属性以及相对应的CSS方法
align="left" float: left;
align="right" float: right;
align="center" margin-right: auto;
margin-left: auto;
text-align: center;
------------------------------------------------------
------------------------------------------------------
40.链接的样式有顺序
顺序为:a:link a:visited a:hover a:active
a:link{font-weight : bold ;text-decoration : none ;color : #c00 ;}
a:visited {font-weight : bold ;text-decoration : none ;color : #c30 ;}
a:hover {font-weight : bold ;text-decoration : underline ;color : #f60 ;}
a:active {font-weight : bold ;text-decoration : none ;color : #F90 ;}
------------------------------------------------------
------------------------------------------------------
41.用图案代替普通无序列表前的黑点
ul.inventory
{
list-style: disc url(/go.jpg) inside;
}
<ul class="inventory">
<li><a href="/angelfish">Angelfish</a>(67 items)</li>
<li><a href="/angeld">Angels/Frogfish</a>(35 items)</li>
<li><a href="/anthias">Angelfish</a>(5526 items)</li>
<li><a href="/basslets">Angelfish</a>(15 items)</li>
</ul>
------------------------------------------------------
------------------------------------------------------
42.收藏夹小图标
代码嵌入 head 区
即收藏夹网址之前的 IE 图标变成了本站特别的图标
<link rel="icon" href="/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
------------------------------------------------------
------------------------------------------------------
43.定义语言编码
代码嵌入 head 区
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
------------------------------------------------------
------------------------------------------------------
44.为搜索引擎准备的内容
代码嵌入 head 区
允许搜索机器人搜索站内所有链接。如果你想某些页面不被搜索,推荐采用 robots.txt 方法:<meta content="all" name="robots" />
设置站点作者信息:<meta name="author" content="ajie@netease.com,阿捷" />
设置站点版权信息:<meta name="Copyright" content="www.w3cn.org,*版权,任意转载" />
站点的简要介绍(推荐):<meta name="description" content="新网页设计师。web 标准的教程站点,推动 web 标准在中国的应用" />
站点的关键词(推荐):<meta name="keywords" content="designing, with, web, standards,w3c, w3, w3cn, ajie" />
------------------------------------------------------
------------------------------------------------------
45.在样式表一开始就先定义所有元素,防止不同浏览器之间的冲突
* {margin:0; padding:0;}
------------------------------------------------------
------------------------------------------------------
46.javascript动态给div添加事件
其中header为div的id:
document.getElementById ("header").onmousedown = test ;
function test()
{
if(window.event.button == 1)
{
alert ("左");
}
}
此javascript代码应该写到div的后面
------------------------------------------------------
------------------------------------------------------
47.在线人数统计思路
利用Ajax技术定时(如5分钟)访问后台程序,后台程序功能如下:
1.更新activetime
2.删除5分钟内未活动人
3.拿到最新在线人数
ALTER PROC [dbo].[SP_SMS_CheckUpdate]
@Username varchar(255),
@ReturnID OUTPUT
/*
功能:
1.更新activetime
2.删除5分钟内未活动人
3.拿到最新在线人数
参数:
@Username 用户名
返回值:
=>0 在线人数
*/
AS
SET NOCOUNT ON
BEGIN
--更新在线时间
UPDATE UDS_Online
SET ActiveTime=getdate()
WHERE Username=@Username
--删除5分钟钟未活动人员
DELETE
FROM
UDS_Online
WHERE DATEDIFF(n,ActiveTime,getdate())>5
SELECT @ReturnID=Count(*)
FROM
UDS_Online
END
SET NOCOUNT OFF
------------------------------------------------------
------------------------------------------------------
48.Page.Cache与HttpContext.Current.Cache区别
指的是同一个对象,
在Page里,用Page.Cache,
如果在global.asax或自己的类里用:HttpContext.Current.Cache,
在有些事件中,由于其没有HttpContext,就用HttpRuntime.Cache
------------------------------------------------------
------------------------------------------------------
49. 绑定treeview
数据库结构:
menuID content parentID
1 一级 0
2 科技 1
3 沈阳 2
4 二级 0
5 美食 4
6 哈尔滨 5
7 三级 0
8 美食 7
9 大连 8
private void LoadTree()
{
treeView1.Nodes.Clear(); //先清空树
DataTable dt = ds.Tables[0]; //把表结构从数据库查出来放到DataTable中
//循环绑定父节点
foreach (DataRow dr in dt.Rows)
{
//遍历加载父节点
if (Convert.ToInt32(dr["parentID"]) == 0)
{
TreeNode newNode = new TreeNode();
newNode.Text = dr["content"].ToString();
newNode.NavigateUrl = "Switch.aspx?id=" + dr["menuID"].ToString();
newNode.Target = "main";
treeView1.Nodes.Add(newNode);
ChildLoad(dr, newNode.ChildNodes, dt);
}
}
this.treeView1.ExpandAll();
}
//绑定子节点
private void ChildLoad(DataRow dr, TreeNodeCollection newNode, DataTable dt)
{
foreach (DataRow row in dt.Rows)
{
if (Convert.ToInt32(dr["menuID"]) == Convert.ToInt32(row["parentID"]))
{
TreeNode childNode = new TreeNode();
childNode.Text = row["content"].ToString();
childNode.NavigateUrl = "Switch.aspx?id=" + row["menuID"].ToString();
childNode.Target = "main";
newNode.Add(childNode);
ChildLoad(row, childNode.ChildNodes, dt); //递归子节点
}
}
}
------------------------------------------------------
------------------------------------------------------
50.发生错误后记录错误日志并转到错误页面
Global.asax中
void Application_Error(object sender, EventArgs e)
{
//可将下面的错误内容写到记事本中作为日志
Exception objErr = Server.GetLastError().GetBaseException();
string error = "发作异常页: " + Request.Url.ToString() + "<br>";
error += "异常消息: " + objErr.Message + "<br>";
Response.Redirect("~/Error.aspx");
}
------------------------------------------------------
------------------------------------------------------
51.关闭页面时清除所有的session
在登录的页面中加上如下代码:
protected void Page_Load(object sender, EventArgs e)
{
Session.Clear(); //清除所有的session
}
------------------------------------------------------
------------------------------------------------------
52.javascript调用后台方法、变量、session
前台:
<script language="javascript" type="text/javascript">
var lpServerIP = "<%=getIpServerIP()%>";
var lPort = "<%=iPort %>";
var session = '<%=Session["test"].ToString() %>';
alert (lpServerIP);
alert (lPort);
alert (session);
</script>
后台:
protected int iPort;
protected void Page_Load(object sender, EventArgs e)
{
iPort = 11;
Session["test"] = "test";
}
public string getIpServerIP()
{
string ipServerIP = "192.168.2.180";
return ipServerIP;
}
------------------------------------------------------
------------------------------------------------------
53.给table加边框
<table border="1" cellpadding="0" cellspacing="0">
------------------------------------------------------
------------------------------------------------------
54.在同一个页面定位方法
即:同一页面中有一个按纽,点击他后定位到网页的中间某位置
<a name="#top" href="#font">top</a>
<a name="#font" href="#top">font</a>
将这两行代码放在你的asp.net 的body的最两极就能看出效果来了
------------------------------------------------------
------------------------------------------------------
55.异步调用服务端注册客户端脚本新方法
//Ajax框架中新调用方式
ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "UpdateSucceed", "alert('Update time succeed!')", true);
//默认调用方式(在异步调用XmlHttp方式中无效)
//Page.ClientScript.RegisterStartupScript(this.GetType(), "UpdateSucceed", "<script>alert('Update time succeed!')</script>");
------------------------------------------------------
------------------------------------------------------
56. 2秒后载入指定网页
<head runat="server">
<meta http-equiv="refresh" content="2;URL=http://localhost:1660/WebSite1/Default.aspx"/>
</head>
------------------------------------------------------
------------------------------------------------------
57.遍历页面中所有的TextBox,将值设置成"a"
for (int j = 0; j < this.Controls.Count; j++) //这个只能找到Form控件,不含容器控件中的其他控件
{
foreach (object o in Page.Controls[j].Controls)
{
if (o is TextBox)
{
TextBox txt = (System.Web.UI.WebControls.TextBox)o;
txt.Text = "a";
}
}
}
或
foreach (Control c in Page.Controls)
{
foreach (Control childc in c.Controls)
{
if (childc is TextBox)
{
TextBox txt = (System.Web.UI.WebControls.TextBox)o;
txt.Text = "a";
}
}
}
最好采用遍历的方法:前面的方法都是当TextBox在Form中的时候可以,
但是当TextBox在Panel中,并且Panel在Form中就不好用了
protected void Page_Load(object sender, EventArgs e)
{
FindControl(Page);
}
private void FindControl(Control control)
{
foreach (Control c in control.Controls)
{
if (c is TextBox)
{
(c as TextBox).Text = "af";
}
if (c.Controls.Count > 0)
{
FindControl(c);
}
}
}
------------------------------------------------------
------------------------------------------------------
58. document.location与window.location的区别:
用户不能改变document.location(因为这是当前显示文档的位置)。但是,可以改变window.location(用其它文档取代当前文档)
window.location本身也是一个对象,而document.location不是对象
------------------------------------------------------
------------------------------------------------------
59.页面刷新后显示刷新前页面的位置
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
MaintainScrollPositionOnPostback ="true" %>
------------------------------------------------------
------------------------------------------------------
60.获取Repeater、Gridview行的序号
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<%#Container.ItemIndex %>
</ItemTemplate>
</asp:Repeater>
<asp:GridView ID="GridView2" runat="server">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<%#Container.DataItemIndex %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<asp:GridView>
------------------------------------------------------
------------------------------------------------------
61.文本框只能输入数字
<input onkeyup="this.value=this.value.replace(/\D/g,'')">
------------------------------------------------------
------------------------------------------------------
62.js获取界面元素
var hidden = document.getElementById ("<%=HiddenField1.ClientID%>");
------------------------------------------------------
------------------------------------------------------
63.防止session过期,可以在Global.asax中设置过期时间
void Session_Start(object sender, EventArgs e)
{
Session.Timeout = 24 * 60; //Session过期时间为1天
}
------------------------------------------------------
------------------------------------------------------
64.将datatable里符合条件的记录取出添加到另一个datatable
DataTable dt = GetData();
DataTable newDT = new DataTable();
newDT = dt.Clone();
DataRow[] rows = dt.Select("parentID=0");
foreach (DataRow row in rows)
{
newDT.ImportRow(row);
}
------------------------------------------------------
------------------------------------------------------
65.FileUpload控件禁止手动输入或粘贴
<asp:FileUpload ID="fu" runat="server" onkeydown="event.returnValue=false;" onpaste="return false" />
------------------------------------------------------
------------------------------------------------------
66.FileUpload类中FileUpload1.FileName和FileUpload1.PostedFile.FileName的区别
比如FileUpload1中的完整路径名是F:\qq\china.txt
那么FileUpload1.FileName的值为china.txt
FileUpload1.PostedFile.FileName的值为F:\qq\china.txt
------------------------------------------------------
------------------------------------------------------
67.TextBox,属性设为TextMode="Password",后台为其赋值,
前台以"***"的形式显示?
TextBox1.Attributes.Add("value","abc");
------------------------------------------------------
------------------------------------------------------
68.DIV水平居中(兼容ff和ie)
1.这个DIV必须有width固定值
2.text-align: center;
margin: 0 auto;
------------------------------------------------------
------------------------------------------------------
69.判断浏览器是否为IE
function isIE() {
return (document.all && window.ActiveXObject && !window.opera) ? true : false;
}
------------------------------------------------------
------------------------------------------------------