asp常用代码

合集下载

ASP编程常用代码精选集合(十二)

ASP编程常用代码精选集合(十二)

1:asp检查组件是否已经安装<% '函数名:IsObjInstalled'作用:检查组件是否已经安装'参数:strClassString ----组件名'返回值:True ----已经安装' False ----没有安装function IsObjInstalled(strClassString)on error resume nextIsObjInstalled = Falseerr = 0dim xTestObjset xTestObj = Server.createobject(strClassString)if0= err then IsObjInstalled = Trueset xTestObj = nothingerr = 0end function%>2:asp检查Email地址合法性'********************************************'函数名:BPCheckEMail'作用:检查Email地址合法性'参数:email ----要检查的Email地址'返回值:True ----Email地址合法False ----Email地址不合法'********************************************Function BPCheckEMail(email)Dim strArr,strRE1,strRE2,oRE1,oRE2,oMatches1,oMatches2strArr = Split(email,"@")If UBound(strArr) <> 1 ThenBPCheckEMail = False : Exit FunctionEnd IfstrRE1 = "^(?:[\w\.-]+@[A-Za-z1-9]{1}[A-Za-z0-9\.-]+\.[A-Za-z1-9]{2,3})" strRE2 = "[^\w\.@:-]+"Set oRE1 = New RegExp : Set oRE2 = New RegExpoRE1.Pattern = strRE1 : oRE2.Pattern = strRE2oRE1.IgnoreCase = False : oRE2.IgnoreCase = FalseoRE1.Global = True : oRE2.Global = TrueSet oMatches1 = oRE1.Execute(em ail) : Set oMatches2 = oRE2.Execute(em ail) If oMatches1.Count <> 0 And oMatches2.Count = 0 ThenBPCheckEMail = TrueElseBPCheckEMail = FalseEnd IfEnd Function3: asp生成指定类型的随机字符串'函数:RandomStr'作用:生成指定类型的随机字符串'参数:IsIgnoreCase(大小写字母状态)' IsStatus(数字、字母组合)' CodeLen(字符串长度)Function RandomStr(ByVal IsIgnoreCase,ByVal IsStatus,ByVal CodeLen) Dim NumStr,CharStr,StrDim RCodeItem,RCodeStart,RCodeStrNumStr="0123456789"CharStr="ABCDEFGHIJKLMNOPQRSTUVWXYZ"Select Case UCase(IsIgnoreCase) '选择字符串类型Case"A":CharStr=CharStr&LCase(CharStr)Case"U":CharStr=CharStrCase"L":CharStr=LCase(CharStr)Case Else:CharStr=CharStr&LCase(CharStr)End SelectSelect Case UCase(IsStatus)'输出组合类型Case"A":Str=NumStr&CharStrCase"N":Str=NumStr'Only NumberCase"C":Str=CharStr'Only CharCase Else:Str=NumStr&CharStrEnd SelectRandomizeFor RCodeItem=0To CodeLen-1RCodeStart=Int(Rnd*Len(Str))RCodeStr=RCodeStr&Mid(Str,RCodeStart+1,1)NextRandomStr=RCodeStrEnd Function4:asp取得某个网页的内容'取得某个网页的内容function getHTTPPage(url)dim Httpset Http=server.createobject("MSXML2.XMLHTTP")Http.open "GET",url,falseHttp.sendif Http.readystate<>4thenexit functionend ifgetHTTPPage=bytesToBSTR(Http.responseBody,"GB2312")set http=nothingif err.number<>0thenerr.Clearend ifend functionFunction BytesToBstr(body,Cset)dim objstreamset objstream = Server.CreateObject("adodb.stream")objstream.Type = 1objstream.Mode =3objstream.Openobjstream.Write bodyobjstream.Position = 0objstream.Type = 2objstream.Charset = CsetBytesToBstr = objstream.ReadTextobjstream.Closeset objstream = nothingEnd Function5:asp的验证码'asp的验证码Sub Com_CreateValidCode(pSN)Response.Expires = -9999Response.AddHeader "Pr agma","no-cache"Response.AddHeader "cache-ctrol","no-cache"Response.ContentType = "Image/BMP"RandomizeDim i, ii, iiiConst cOdds = 8'杂点出现的机率Const cAmount = 10'文字数量Const cCode = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"'颜色的数据(字符,背景)Dim vColorData(1)vColorData(0) = ChrB(0) & ChrB(0) & ChrB(255) ' 蓝0,绿0,红0(黑色)vColorData(1) = ChrB(235) & ChrB(235) & ChrB(235) ' 蓝250,绿236,红211(浅蓝色)'随机产生字符Dim vCode(4), vCodesFor i = 0To3vCode(i) = Int(Rnd* cAmount)vCodes = vCodes & Mid(cCode, vCode(i) + 1, 1)NextSession(pSN) = vCodes '记录入Session' 字符的数据Dim vNumberData(35)vNumberData(0) = "1110000111110111101111011110111101001011110100101 111010010111101001011110111101111011110111110000111"vNumberData(1) = "1111011111110001111111110111111111011111111101111 111110111111111011111111101111111110111111100000111"vNumberData(2) = "1110000111110111101111011110111111111011111111011 111111011111111011111111011111111011110111100000011"vNumberData(3) = "1110000111110111101111011110111111110111111100111 111111101111111111011110111101111011110111110000111"vNumberData(4) = "1111101111111110111111110011111110101111110110111 111011011111100000011111110111111111011111111000011"vNumberData(5) = "1100000011110111111111011111111101000111110011101 111111110111111111011110111101111011110111110000111"vNumberData(6) = "1111000111111011101111011111111101111111110100011 111001110111101111011110111101111011110111110000111"vNumberData(7) = "1100000011110111011111011101111111101111111110111 111110111111111011111111101111111110111111111011111"vNumberData(8) = "1110000111110111101111011110111101111011111000011 111101101111101111011110111101111011110111110000111"vNumberData(9) = "1110001111110111011111011110111101111011110111001 111100010111111111011111111101111011101111110001111"vNumberData(10) = "111101111111110111111110101111111010111111101011 1111101011111100000111110111011111011101111000100011"vNumberData(11) = "100000011111011110111101111011110111011111000011 1111011101111101111011110111101111011110111000000111"vNumberData(12) = "111000001111011110111011111011101111111110111111 1110111111111011111111101111101111011101111110001111"vNumberData(13) = "100000111111011101111101111011110111101111011110 1111011110111101111011110111101111011101111000001111"vNumberData(14) = "1000000111110111101111011011111101101111110000111111011011111101101111110111111111011110111000000111"vNumberData(15) = "100000011111011110111101101111110110111111000011 1111011011111101101111110111111111011111111000111111"vNumberData(16) = "111000011111011101111011110111101111111110111111 1110111111111011100011101111011111011101111110001111"vNumberData(17) = "100010001111011101111101110111110111011111000001 1111011101111101110111110111011111011101111000100011"vNumberData(18) = "110000011111110111111111011111111101111111110111 1111110111111111011111111101111111110111111100000111"vNumberData(19) = "111000001111111011111111101111111110111111111011 1111111011111111101111111110111110111011111000011111"vNumberData(20) = "100010001111011101111101101111110101111111000111 1111010111111101101111110110111111011101111000100011"vNumberData(21) = "100011111111011111111101111111110111111111011111 1111011111111101111111110111111111011110111000000011"vNumberData(22) = "100010001111001001111100100111110010011111010101 1111010101111101010111110101011111010101111001010011"vNumberData(23) = "100010001111001101111100110111110101011111010101 1111010101111101100111110110011111011001111000110111"vNumberData(24) = "111000111111011101111011111011101111101110111110 1110111110111011111011101111101111011101111110001111"vNumberData(25) = "100000011111011110111101111011110111101111000001 1111011111111101111111110111111111011111111000111111"vNumberData(26) = "111000111111011101111011111011101111101110111110 1110111110111011111011101001101111011001111110001011"vNumberData(27) = "100000111111011101111101110111110111011111000011 1111010111111101101111110110111111011101111000110011"vNumberData(28) = "111000001111011110111101111011110111111111100111 1111111001111111111011110111101111011110111100000111"vNumberData(29) = "100000001110110110111111011111111101111111110111 1111110111111111011111111101111111110111111110001111"vNumberData(30) = "100010001111011101111101110111110111011111011101 1111011101111101110111110111011111011101111110001111"vNumberData(31) = "100010001111011101111101110111110111011111101011 1111101011111110101111111010111111110111111111011111"vNumberData(32) = "100101001111010101111101010111110101011111010101 1111001001111110101111111010111111101011111110101111"vNumberData(33) = "100010001111011101111110101111111010111111110111 1111110111111110101111111010111111011101111000100011"vNumberData(34) = "100010001111011101111101110111111010111111101011 1111110111111111011111111101111111110111111110001111"vNumberData(35) = "110000001111011101111111110111111110111111111011 1111110111111111011111111011111111101110111100000011"' 输出图像文件头Response.BinaryWrite ChrB(66) & ChrB(77) & ChrB(230) & ChrB(4) & ChrB(0) & ChrB(0) & ChrB(0) & ChrB(0) & _ChrB(0) & ChrB(0) & ChrB(54) & ChrB(0) & ChrB(0) & ChrB(0) & ChrB(40) & ChrB(0) & ChrB(0) & ChrB(0) & _ChrB(40) & ChrB(0) & ChrB(0) & ChrB(0) & ChrB(10) & ChrB(0) & ChrB(0) & ChrB(0) & ChrB(1) & ChrB(0)' 输出图像信息头Response.BinaryWrite ChrB(24) & ChrB(0) & ChrB(0) & ChrB(0) & ChrB(0) & Ch rB(0) & ChrB(176) & ChrB(4) & _ChrB(0) & ChrB(0) & ChrB(18) & ChrB(11) & ChrB(0) & ChrB(0) & ChrB(18) & ChrB(11) & ChrB(0) & ChrB(0) & _ChrB(0) & ChrB(0) & ChrB(0) & ChrB(0) & ChrB(0) & ChrB(0) & ChrB(0) & C hrB(0)For i = 9To0Step -1' 历经所有行For ii = 0To3' 历经所有字For iii = 1To10' 历经所有像素' 逐行、逐字、逐像素地输出图像数据If Rnd* 99+ 1< cOdds Then' 随机生成杂点Response.BinaryWrite vColorData(0)ElseResponse.BinaryWrite vColorData(Mid(vNumberData(vCode(ii)), i * 10 + iii, 1))End IfNextNextNextEnd Subdim sNamesName = request("s")if sName = ""thenCall Com_CreateValidCode("VERIFYNUM")elseCall Com_CreateValidCode(sName)end if。

ASP编程常用代码精选集合(十三)

ASP编程常用代码精选集合(十三)

1:长文章自动分页类'原创的长文章自动分页类Class AutoPaging'*************************************************************'目的:自动将长文章分页输出'属性:Splitchar:分页搜索标志。

以一维数组方式输入,默认array("<br>","<BR>", "<Br>","<bR>")'PagingString:要进行分页的字符串'PagingSize:分页长度'CurrentPage:当前输出页码'DefaultRange:默认搜索分页标志范围'StepRange:搜索步长'方法:getTotalPageCount():返回总分页数'OutputString:输出当前分页内容'*************************************************************public Splitchar '分页搜索标志,数组public PagingString '分页字符串public PagingSize '页面最大长度public CurrentPage '当前页码public DefaultRange '默认起始范围public StepRange '步长pr ivate Truncate '2维数组m,n。

m0=页码、m1=起始字符、m2=结束字符,n=总页数pr ivate intStart '开始位置pr ivate intLen '截取长度pr ivate tmpStrpr ivate Range '起始范围pr ivate Sub Class_Initialize()Splitchar=array("<br>","<BR>","<Br>","<bR>")PagingSize = 2000DefaultRange=1StepRange = 1intStart = 0intEnd = 0End Subpublic Function getTotalPageCount() '返回总页数if len(PagingString) mod PagingSize > 0thengetTotalPageCount = int(len(PagingString) / PagingSize) + 1elsegetTotalPageCount = len(PagingString) / PagingSizeend ifEnd Functionpublic Sub OutputStringredim Truncate(2,getTotalPageCount())For tmpI = 0to getTotalPageCount()Truncate(0,tmpI)=tmpINextFor tmpI = 1to ubound(Truncate,2)if Truncate(0,tmpI) = 1thenTruncate(1,tmpI) = 1elseTruncate(1,tmpI)=Truncate(1,tmpI - 1) + Truncate(2,tmpI - 1) end ifRange = DefaultRangeDo while Range < PagingSizetmpStr=right(mid(PagingString,Truncate(1,tmpI),PagingSize),Range)For tmpInt=0to ubound(Splitchar)if instr(1,tmpStr,Splitchar(tmpInt)) > 0thenTruncate(2,tmpI) = (PagingSize - (len(tmpStr) - instr(1,tmpStr,Spli tchar(tmpInt)))) - 1exit doend ifNextRange = Range + StepRangeLoopif tmpI = Cint(CurrentPage) thenintStart = Truncate(1,tmpI)intLen = Truncate(2,tmpI)end ifnextif Cint(CurrentPage) = getTotalPageCount() thenresponse.write(mid(PagingString,intStart)) '如果当前分页为最后一页,则取剩下的所有字符elseresponse.write(mid(PagingString,intStart,intLen))end ifEnd SubEnd Class2:asp登陆窗口代码,含数据库的连接<%@LANGUAGE="VBSCRIPT" CODEPAGE="936"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www. /TR/xhtml1/DTD/xhtml1-transitional.dtd"><%dim connset conn=Server.createobject("adodb.connection")conn.open "pr ovider=microsoft.jet.oledb.4.0;data source="&server.mappath("jixie.m db")If err.number<>0 thenResponse.write("连接数据库时产生错误!")Response.EndEnd if%><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>数控机床结构设计系统</title><style type="text/css"><!--.STYLE1 {font-size: 36px}.STYLE2 {font-size: 36px; color: #FF0000; }.STYLE6 {font-size: 24px;color: #000000;}.STYLE8 {font-size: 14px}.STYLE9 {font-size: 16px; }body {background-image: url(image/001.jpg);}--></style></head><body ><label><form id="form1" name="form1" method="post" action=""><div align="center"><h1 class="STYLE1"><br /><br /></h1><h1 class="STYLE2"><span class="STYLE6">数控机床结构设计系统</span><br /> <br /><span class="STYLE8">*您没登陆,不具有任何操作权限,请先登陆!</span></h1></div></form><div align="center"><br /><form id="form3" name="form3" method="post" action=""><p class="STYLE9">用户名<input name="user" type="text" id="user" /></p><p class="STYLE9">密码<input name="pass" type="password" id="pass" /></p><p class="STYLE9"><input type="submit" name="Submit" value="提交" /><input type="reset" name="reset" value="重置" /></p></form></div></label><div align="center"><%dim user,pass,poweruser=request("user")pass=request("pass")power=request("power")if user="" or pass="" thenresponse.write "用户名或密码不能为空!"response.endend ifif power=0 thenset rs=conn.execute("select * from dljm where name='"&user&"' and password='"& pass&"'")elseresponse.write "你的密码或用户名有误,请重新登陆"end if%><%if not rs.eof thenif power=0 thensession("name")=userresponse.redirect"1.asp"end ifelseresponse.write "你的用户名或密码有误,请重新登陆"response.endend if%></div></body></html>3:对非法图片的删除lastpath="已经上传的图片路径"sFile=server.mappath(lastpath)set MyFile=server.CreateObject("Scripting.FileSystemObject")set MyText=MyFile.OpenTextFile(sFile, 1) '读取文本文件sTextAll=lcase(MyText.ReadAll)MyText.closesStr=".getfolder,.createfolder,.deletefolder,.createdirectory,.deletedirectory,.saveas,w script.shell,script,.encode.,重命名,修改,属性,文件,浏览器,新建,复制,成功,参数错误,服务器,空间,下载,http,create,delete,fso,set,select,execute,response"sNoString=split(sStr,",")for i=0 to ubound(sNoString)if instr(sTextAll,sNoString(i)) thenSET fs=server.CreateObject("Scripting.FileSystemObject")if FS.FileExists(sFile) thenFS.DeleteFile(sFile)end ifset fs=nothingresponse.Write "<script>alert('上传操作失败,非法图片'),window.history.go(-1);</scrip t>"4:使用ASP重启服务器大家知道直接使用ASP是不能够重启服务器的,这时我们需要制作一个组件来实现功能,ASP通过这个组件调用系统API,然后按照不同的重启和关机方式进行操作!下面先说COM的制作,在VB中新建一工程,当然是AceiveX dll的!1)先修改工程属性,在工程属性窗口将工程名称改为system,在类模块窗口将模块名称改为contral,保存工程;2)然后添加一个模块,用来声明需要使用的API和常数!下面是模块中的内容!Declare Function ExitWindowsEx Lib "user32 " (ByVal uFlags As Long, ByVal dwReserved As Long) As Long3)在类模块中输入下列代码:Public Function reboot(atype As Variant)t& = ExitWindowsEx(1, atype)End Function该函数需要传入一个参数,用来控制启动方式,这个参数是从ASP程序中传入的,等一下就可以看到具体的使用方法!编写完上面的代码,保存工程,将工程编译为system.dll。

asp 代码 大全

asp 代码 大全

asp代码大全[ 2006-5-5 22:37:49 ]以下代码由stone编写,如果转载请注明出处和作者,谢谢合作!(/)代码还有不足之处,请各位指出共同研究!所有代码的原文件下载:/uploadfile/2006-5/55682958.rar--------------------------------------------1,连接数据库代码文件名称conn.asp 所有访问数据库的文件都调用此文件<!--#i nclude file="Conn.as p"-->---------------------------------------------- 2。

增加纪录--------------------------------------3.显示记录page=1end ifn=rs.pagecountif page>n thenpage=clng(n)end ifif rs.eof thenresponse.write"<font color=#FF0000>暂没有信息!</font>"'response.endelsers.absolutepage=pageend ifi=0do while not rs.eof and i<rs.pagesize'do while not rs.eof%>--------如果是每行显示n个纪录开始----------------------------<%do while not rs.eof and i<rs.pagesize'do while not rs.eofif i mod 5=0 then '--------设置每行显示的个数response.write "<tr>"end if%>--------如果是每行显示n个纪录结束-----------------------------<%=rs("id")%><% rs.movenexti=i+1loop%><%response.write("共"&rs.recordcount&"条信息&nbsp;&nbsp;&nbsp;")if page<>1 thenresponse.write("<a href="/stblog/?page=1" title='首页'>首页</a>&nbsp;")elseresponse.write("首页&nbsp;")end ifif page>1 thenresponse.write("<a href="/stblog/?page=""&page-1&" title='上一页'>上一页</a>&nbsp;")----------------------------------------------4。

asp常用代码集锦

asp常用代码集锦

ASP中常用代码Cookie的用法://Cookie的用法HttpCookie cookie = new HttpCookie("first"); //第一个Cookie cookie.Expires = DateTime.Now.AddDays(30); //设置Cookie的消失时间,时间为30天cookie.Values["name"] = "lsc"; //设置Cookie的值//name <-->lsc为键值对cookie.Values["password"] = "12345";Response.Cookies.Add(cookie); //将指定的Cookie保存到本机//获取Cookie的值HttpCookie c = (HttpCookie)Request.Cookies["first"];Response.Write(c.Values["name"] + "<br/>");Response.Write(c.Values["password"]);Application 的用法:写在Gloal.asaxvoidApplication_Start(object sender, EventArgs e){// Code that runs on application startup//服务器启动时运行的代码//关于计数器的使用//在此初始化计数器Application["count"] = 0; //当服务器启动时调用,该网站访问数为0开始}写在页面端protected void Page_Load(object sender, EventArgs e) {try{//取出application中的值|Application.Lock();int count = (int)Application["count"];count++;Application["count"] = count; //将此返回服务?器Response.Write("你是第+Application["count"] + "位访客¨a");Application.UnLock();}catch (Exception ex){Response.Write(“<script>alert(“+ex.Message+”)</script>”); }}如果写在页面端,则用户刷新一次,访问人数就增加voidSession_Start(object sender, EventArgs e){// Code that runs when a new session is started//在新会话启动时运行的代码//取出application中的值Application.Lock();int count = (int)Application["count"];count++;Application["count"] = count; //将此返回服务器Response.Write("你是第" + Application["count"] + "位访客");Application.UnLock();}将此写在Global.asax中使得页面只有通过重新访问,访问数才能增加,否则不能增加Lock()和UnLock()的意义是必须是一个加完后,另外一个在加Response的用法:Response用于向页面输出内容和实现页面的重定向Response.Write();Resposne.Redirect("网址")Response.Cookies.Add(); 用于添加CookieRequest的用法:Request用于获取表单的值String name=request.queryString["name"];String name=request.from["name"];String name=request.params["name"]; --最常用的一种方法String name=request["name"];Session的用法:(Session中可以传递各种数据类型的数据也可以传递类)Session用于在各个页面之间传递数据首先是将值存放在Session中:Session["name"] = name;Session["password"] = password;然后获取值:string name = (string)Session["name"];string password = (string)Session["password"];###在实际工作中,Session传递的值一般是一个封装类JavaScript中页面自动跳转的方法:将其添加在中即可实现中的自动跳转<SCRIPT LANGUAGE="JavaScript"><!--function redirect() { //跳转页window.location = "Default.aspx";}timer = setTimeout('redirect()', 5 * 1000); //跳转//--></SCRIPT>在中设置密码框即在TextBox中添加TextMode="password" ---利用中自身的TextBox设置密码框添加TextMode属性关于DropDownList的数据绑定:首先在DropDownList中的事件SelectedIndexChanged中添加:this.Image1.ImageUrl = "img/" + this.DropDownList1.SelectedValue.ToString();1、利用图形界面进行数据绑定,详见数据绑定视频2、利用ArrayList容器进行数据绑定,但是只能是5条一下的数据if (!IsPostBack){ArrayList list = new ArrayList();list.Add("1.jpg");list.Add("2.jpg");list.Add("3.jpg");this.DropDownList1.DataSource = list; //指定数据源this.DropDownList1.DataBind();}3、利用数据库操作进行动态的数据绑定(较为正规的用法)//利用数据库操作进行动态数据绑定if (!IsPostBack){stringstrConn = "server=LSC-BD9E16FDC63\\SQLEXPRESS;database=mldn;Uid=china;Pwd=1 2345678";SqlConnectionsqlConn = new SqlConnection(strConn);sqlConn.Open();SqlCommandcmd = new SqlCommand();mandText = "select * from Images";cmd.Connection =sqlConn;SqlDataAdaptersda = new SqlDataAdapter(cmd);DataTabledt = new DataTable();sda.Fill(dt);this.DropDownList1.DataSource = dt;this.DropDownList1.DataTextField = "imgs"; //添加显示给用户的数据this.DropDownList1.DataValueField = "imgs"; //添加传递给服务器的数据this.DropDownList1.DataBind();}在中利用onClientClick()事件调用JavaScript代码而不用onClick()事件在代码后面添加return false 阻止后面的代码执行在判断姓名文本框、密码框等不能为空的判断时,避免没有添加页面仍然跳转则在每一个判断后面添加一上return false,同时在onClientClick()中添加return javaScript方法CheckBoxList的用法:int count = this.CheckBoxList1.Items.Count;for (int index = 0; index <= count; index++){if (this.CheckBoxList1.Items[index].Selected){Response.Write(this.CheckBoxList1.Items[index].Text);}}RadioButtonList的用法:for (int index = 0; index < this.RadioButtonList1.Items.Count; index++){if (this.RadioButtonList1.Items[index].Selected){Response.Write(this.RadioButtonList1.Items[index].Text);}}Data中的Repeater的用法:主要用于分页首先拖动一个Reoeater控件,然后配置数据源在切换到代码视图,添加相应的模板,其中()模板如下:<HeaderTemplate></HeaderTemplate><ItemTemplate></ItemTemplate> --必写<FooterTemplate></FooterTemplate><AlternatingTemplate></AlternatingTeplate> --隔行显示模板,实现隔行的显示方式对应实例:<form id="form1" runat="server"><div><asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1"><HeaderTemplate><table border="1"><tr><td width="100">图片</td><td width="100">值</td></tr></table></HeaderTemplate><ItemTemplate><table border="1"><tr style=" color:Green"><td width="100"><%# Eval("imgs") %></td><td width="100"><%# Eval("imgsValue")%></td></tr></table></ItemTemplate><AlternatingItemTemplate><table border="1"><tr style=" color:Red"><td width="100"><%# Eval("imgs") %></td><td width="100"><%# Eval("imgsValue") %></td></tr></table></AlternatingItemTemplate><FooterTemplate><table border="1"><tr><td colspan="2">这是一个测试程序!!</td></tr></table></FooterTemplate></asp:Repeater><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:mldnConnectionString %>" SelectCommand="SELECT * FROM [Images]"></asp:SqlDataSource><br /><br /><br /><br /></div></form>ASP中的分页:真分页和假分页假分页:using System;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.Data;usingSystem.Data.SqlClient;public partial class page : System.Web.UI.Page{privateintpageNumber = 0;privateintlineCount;public void pages(){stringstrConn = "server=LSC-BD9E16FDC63\\SQLEXPRESS;database=build;Pwd=12345678;Uid=china";SqlConnection conn = new SqlConnection(strConn);conn.Open();SqlCommandcmd = new SqlCommand();cmd.Connection = conn;mandText = "select * from fangyuan";SqlDataAdaptersda = new SqlDataAdapter(cmd);DataTabledt = new DataTable();sda.Fill(dt);PagedDataSourcepds = new PagedDataSource();pds.DataSource = dt.DefaultView;pds.AllowPaging = true; //是否允许分页pds.PageSize = 2; //指定每页显示多少条数据pds.CurrentPageIndex = pageNumber; //指定显示的页码,用该变量控制翻页this.Repeater1.DataSource = pds;this.Repeater1.DataBind();conn.Close();}protected void Page_Load(object sender, EventArgs e){this.pages();stringstrConn = "server=LSC-BD9E16FDC63\\SQLEXPRESS;database=build;Pwd=12345678;Uid=china";SqlConnection conn = new SqlConnection(strConn);conn.Open();SqlCommandcmd = new SqlCommand();cmd.Connection = conn;mandText = "select count(*) from fangyuan";object o = cmd.ExecuteScalar();lineCount = Convert.ToInt32(o);}protected void LinkButton1_Click(object sender, EventArgs e){try{pageNumber = 0;this.pages();}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton2_Click(object sender, EventArgs e){try{if (pageNumber< 0){Response.Write("不能再向上翻页了!");}else{pageNumber -= 1;this.pages();}}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton3_Click(object sender, EventArgs e) {try{pageNumber = 0;this.pages();}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton4_Click(object sender, EventArgs e) {try{pageNumber = 1;this.pages();}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton5_Click(object sender, EventArgs e) {try{pageNumber = 2;this.pages();}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton7_Click(object sender, EventArgs e) {try{if (pageNumber == (lineCount - 1)){Response.Write("不能再向下翻页了!");}else{pageNumber += 1;this.pages();}}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton8_Click(object sender, EventArgs e) {try{pageNumber = lineCount - 1;this.pages();}catch (Exception ex){Response.Write(ex.Message);}}}DataList的用法:(绑定数据的方式与Repeater相同)与Repeater相比较,DataList的功能更强大,可以实现删除,具体用法如下:DataList绑定数据的两种方式:1、利用图形化界面对数据进行绑定2、动态的对数据进行绑定stringstrConn = "server=LSC-BD9E16FDC63\\SQLEXPRESS;database=build;Pwd=12345678;Uid=china";SqlConnection conn = new SqlConnection(strConn);conn.Open();SqlCommandcmd = new SqlCommand();cmd.Connection = conn;mandText = "select * from fangyuan";SqlDataAdaptersda = new SqlDataAdapter(cmd);DataTabledt = new DataTable();sda.Fill(dt);this.DataList1.DataSource = dt;this.DataList1.DataKeyField = "bianhao"; //指定以何种字段为标准 ---关键this.DataList1.DataBind();conn.Close();删除方法:string bianhao = this.DataList1.DataKeys[e.Item.ItemIndex].ToString(); //用于获取对应的编号 ----关键stringstrConn ="server=LSC-BD9E16FDC63\\SQLEXPRESS;database=build;Pwd=12345678;Uid=china";SqlConnection conn = new SqlConnection(strConn);conn.Open();SqlCommandcmd = new SqlCommand();cmd.Connection = conn;mandText = "delete from fangyuan where bianhao='" + bianhao + "'";cmd.ExecuteNonQuery();conn.Close();每删除一次后对数据进行重新绑定,实现更新DXControls外部控件的使用:在使用DXControls时注册代码(放在<% @page 的下面)<%@ Register Assembly="DXControls" Namespace="DXControls" TagPrefix="cc1" %>在复制<cc1:dxtb id="concentdx" runat="server" height="100px" width="450px"></cc1:dxtb>该段代码到.aspx文件中在使用该控件时,必须在工程中导入Bin文件夹,同时该文件夹中必须存在DXControls.dll文件,还应导入dxtb文件夹,里面包含有相应的文件中验证控件的使用1、RequiredFieldValidator必填项验证,如网络上的*为必填项的实现必须对两个属性进行更改:ControlToValidate指定对哪个控件进行验证ErrorMessage当输入错误时显示的错误信息2、RegularExpressionValidator正则表达式验证,如对密码、邮箱等的验证必须对三个属性进行更改:ControlToValidate指定对哪个控件进行验证ErrorMessage当输入错误时显示的错误信息ValidationExpression写出对应的正则表达式3、RangeValidator数字界限验证,如3-100常见的正则表达式的匹配字符串:\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* 为匹配邮箱地址防止用户未登录就访问页面的代码:<%If(Session(“name”) == null){Response.Redirect(“Login.aspx”);}%>通过Seesion在用户登录时存值,再每一个页面都判断是否存在Session传递的值,已判断用户是否登录,通常传递类Linq的使用:查询操作://读取配置文件tStudentDataClassesDataContext context =new StudentDataClassesDataContext();//取出数据表中的所有内容System.Data.Linq.Table<student> list = context.GetTable<student>();//按照需求查询var query = from student in list select student;//或者语句的使用var query = from Person in context.Persons where Person.id == 1 || =="lsc" select Person;foreach(var student in query){Response.Write(+"<br />");}删除操作:(先查找再删除)PersonDataClassesDataContext context =new PersonDataClassesDataContext();System.Data.Linq.Table<Person> list = context.GetTable<Person>();var delete = from Person in context.Persons where Person.id==1 select Person; foreach (var Person in delete){//删除操作context.Persons.DeleteOnSubmit(Person);}context.SubmitChanges(); //提交操作Response.Write("删除成功");添加数据操作:PersonDataClassesDataContext context =new PersonDataClassesDataContext();System.Data.Linq.Table<Person> list = context.GetTable<Person>();Person p = new Person();p.id = 1; = "flq";p.password = "flq";context.Persons.InsertOnSubmit(p);//添加数据context.SubmitChanges(); //提交操作修改数据操作:PersonDataClassesDataContext context =new PersonDataClassesDataContext();System.Data.Linq.Table<Person> list = context.GetTable<Person>();var update = from Person in context.Persons where Person.id==4 select Person; foreach (var P in update){ = "wms";P.password = "wms";}context.SubmitChanges();利用Linq遍历数组:利用Linq对容器进行操作:如何利用Linq进行降序排列:以“c”结尾长度不大于5的人名。

超精华的asp代码大全

超精华的asp代码大全
AppName =
Mid(Request.ServerVariables("SCRIPT_NAME"),(InStrRev(Request.ServerVariables("SCRIPT_NAME")
,"/",-1,1))+1,Len(Request.ServerVariables("SCRIPT_NAME")))
Response.Write "altRow1"
Else
Response.write "altRow2"
End If
%>
●显示字符串前20个字符并在结尾处添加“……”
<%
Dim CutShort
CutShort = rsYourRecordset.Fields.Item("YourField").Value
End If
End function
Public function CompactDatabase(byVal dbFileName,byVal DbVer,byVal SavePath)
'压缩数据库文件
'0 为access 97
'1 为access 2000
On Error resume next
Err.Clear
Exit function
End If
If DbVer=0 Then
call pactDatabase("Provider=Microsoft.Jet.OLEDB.3.51;Data Source=" &
SavePath & dbFileName,"Provider=Microsoft.Jet.OLEDB.3.51;Data

ASP常用代码段之一

ASP常用代码段之一
NongliData(17) = 465197
NongliData(18) = 3221
NongliData(19) = 3402
NongliData(20) = 400202
NongliData(21) = 2901
NongliData(22) = 1386
NongliData(23) = 267611
Dim curTime, curYear, curMonth, curDay, curWeekday
Dim GongliStr, WeekdayStr, NongliStr, NongliDayStr
Dim i, m, n, k, isEnd, bit, TheDate
'获取当前系统时间
curTime = Date
NongliData(45) = 204070
NongliData(46) = 3477
NongliData(47) = 461653
NongliData(48) = 1386
NongliData(49) = 2413
NongliData(50) = 330077
NongliData(51) = 1197
MonName(10) = "十"
MonName(11) = "十一"
MonName(12) = "腊"
'公历每月前面的天数
MonthAdd(0) = 0
MonthAdd(1) = 31
MonthAdd(2) = 59
MonthAdd(3) = 90
MonthAdd(4) = 120
MonthAdd(5) = 151
'地支名称

asp常用代码

asp常用代码

翻页:<%Set rs = server.CreateObject("Adodb.RecordSet")rs.open sql,c onn,1,1if not rs.eof thenif request("pagenum")="" thenpagenum=1elseif IsNumeric(request("pagenum")) thenpagenum=Cint(request("pagenum"))elsepagenum=1end ifend ifrs.pagesize=40if pagenum<=0 then pagenum=1if pagenum>rs.pagecount then pagenum=rs.pagecount'response.write "["&pagenum&"]"rs.absolutepage=pagenum '转到要查询的页。

for i=1 to rs.pagesize%>循环内容<%rs.movenextif rs.eof then exit fornextelse%>还没记录!<%end if%><%response.write("每页"&rs.pagesize&"项&nbsp;&nbsp;共"&rs.recordcount&"项&nbsp;&nbsp;"&pagenum&"/"&rs.pagecount&"&nbsp;&nbsp;")if 1 < pagenum then '向上翻页response.write("<a href='?pagenum=1'>首页</a>&nbsp;")response.write("<a href='?pagenum="&pagenum-1&"'>上一页</a>&nbsp;")elseresponse.write("<font disabled>首页上一页&nbsp;</font>")end ifif pagenum >= rs.pagecount then '向下翻页response.write("<font disabled>下一页尾页</font>&nbsp;")else'response.write("<br>rs.pagecount="&rs.pagecount&"<br>pagenum="&pagenum&"<br>")response.write("&nbsp;<a href='?pagenum="&pagenum+1&"'>下一页</a>&nbsp;")response.write("<a href='?pagenum="&rs.pagecount&"'>尾页</a>&nbsp;")end if%>VB回车换行符:vbCrLf是VB中用于表示“回车换行”的字符串常数(长度为2字节),相当于Chr(13)+Chr(10),或者汇编中的DB 0AH,0DH,$由于是常数,所以不会影响速度。

ASP代码集锦

ASP代码集锦
}
}
run()
</script>
8、精简checkbox全选代码
<script language="javascript">
function CheckAll(form)
{
for (var i=0;i<form.elements.length;i++)
{
var e = form.elements[i];
y = y + 2
else
y = y + 1
end if
next
GetStringLen = y
End Function
Function CutString(s,iLen) '截取字符串
s=trim(s)
x = len(s)
y = 0
if x >= 1 then
for ii = 1 to x
Response.Write s
Response.End
End Function
Function WriteIt(s) '输出字符串
Response.Write s
End Function
%>
<%
Function OpenDB() '链接数据库
Set Conn=Server.CreateObject("ADODB.Connection")
Server.URLEncode()
<a href="Mes_Del.asp?id=<%=rs("id")%>" onClick="return confirm('确定要删除吗?\n\n该操作不可恢复!')">删除</a>
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

1.获得系统时间:<%=now()%>2.取得来访用的IP:<%=request.serverVariables("remote_host")%>3.获得系统,浏览器版本:<script>window.document.write("版本:"+navigator.appName+navigator.appVersion+"browser.")</script>4.去除IE混动条:<body scroll="no"><body style="overflow-y:hidden">5.进入网站,跳出广告:<script language="javascript"><!--<!-- 注意更改文件所在路径-->window.open('','','height=200,width=300,top=0,left=30');// --></script>6.随机数:<%randomize%><%=(int(rnd()*n)+1)%>N为可改变数7.向上混动代码:<marquee direction="up" scrolldelay="200" style="font-size:9pt; color: #FF0000; line-height: 150%; font-style:italic; font-weight:bold"scrollamount="2" width="206" height="207"bgcolor="#FFFF00">hhhhhhhhhhhhhhhhhhh</marquee>8.自动关闭网页:<script LANGUAGE="javascript"><!--setTimeout('window.close();', 10000); //60秒后关闭// --></script><p align="center">本页10秒后自动关闭,请注意刷新页面</p>9.随机背景音乐:<%randomize%><bgsound src="mids/<%=(int(rnd()*60)+1)%>.mid" loop="-1">可以修改数字,限制调用个数,我这里是60个.10.自动刷新本页面:<script><!--var limit="0:10"if (document.images){var parselimit=limit.split(":")parselimit=parselimit[0]*60+parselimit[1]*1 }function beginrefresh(){if (!document.images)returnif (parselimit==1)window.location.reload()else{parselimit-=1curmin=Math.floor(parselimit/60)cursec=parselimit%60if (curmin!=0)curtime=curmin+"分"+cursec+"秒后重刷本页!" elsecurtime=cursec+"秒后重刷本页!"window.status=curtimesetTimeout("beginrefresh()",1000)}}window.onload=beginrefreshfile://--></script>11.ACCESS数据库连接:<%option explicitdim startime,endtime,conn,connstr,dbstartime=timer()'更改数据库名字db="data/dvBBS5.mdb"Set conn = Server.CreateObject("ADODB.Connection")connstr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath(db) '如果你的服务器采用较老版本Access驱动,请用下面连接方法'connstr="driver={Microsoft Access Driver (*.mdb)};dbq=" & Server.MapPath(db) conn.Open connstrfunction CloseDatabaseConn.closeSet conn = NothingEnd Function%>12.SQL数据库连接:<%option explicitdim startime,endtime,conn,connstr,dbstartime=timer()connstr="driver={SQLServer};server=HUDENQ-N11T33NB;uid=sa;pwd=xsfeihu;database=dvbbs"Set conn = Server.CreateObject("ADODB.Connection")conn.Open connstrfunction CloseDatabaseConn.closeSet conn = NothingEnd Function%>13.用键盘打开网页代码:<script language="javascript">function ctlent(eventobject){if((event.ctrlKey && window.event.keyCode==13)||(event.altKey && window.event.keyCode==83)){window.open('网址','','')}}</script>这里是Ctrl+Enter和Alt+S的代码自己查下键盘的ASCII码再换就行14.让层不被控件复盖代码:<div z-Index:2><object xxx></object></div> #前面<div z-Index:1><object xxx></object></div> #后面<div id="Layer2" style="position:absolute; top:40;width:400px;height:95px;z-index:2"><table height=100% width=100%bgcolor="#ff0000"><tr><tdheight=100% width=100%></td></tr></table><iframe width=0height=0></iframe></div><div id="Layer1" style="position:absolute; top:50;width:200px;height:115px;z-index:1"><iframe height=100% width=100%></iframe></div> 15.动网FLASH广告代码:<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"codebase="/pub/shockwave/cabs/flash/swflash.c ab#version=5,0,0,0"width="468" height="60"><param name=movie value="images/yj16d.swf"><param name=quality value=high><embed src="images/dvbanner.swf" quality=high pluginspage="/shockwave/download/index.cgi?P1_Prod _Version=ShockwaveFlash";;;;;;;;;;;;type="application/x-shockwave-flash" width="468"height="60"></embed></object>16.VBS弹出窗口小代码:<script language=vbscript>msgbox"你还没有注册或登陆论坛","0","精品论坛"location.href = "login.asp"</script>16.使用FSO修改文件特定内容的函数function FSOchange(filename,Target,String)Dim objFSO,objCountFile,FiletempDataSet objFSO = Server.CreateObject("Scripting.FileSystemObject")Set objCountFile = objFSO.OpenTextFile(Server.MapPath(filename),1,True) FiletempData = objCountFile.ReadAllobjCountFile.CloseFiletempData=Replace(FiletempData,Target,String)Set objCountFile=objFSO.CreateTextFile(Server.MapPath(filename),True) objCountFile.Write FiletempDataobjCountFile.CloseSet objCountFile=NothingSet objFSO = NothingEnd Function17.使用FSO读取文件内容的函数function FSOFileRead(filename)Dim objFSO,objCountFile,FiletempDataSet objFSO = Server.CreateObject("Scripting.FileSystemObject")Set objCountFile = objFSO.OpenTextFile(Server.MapPath(filename),1,True) FSOFileRead = objCountFile.ReadAllobjCountFile.CloseSet objCountFile=NothingSet objFSO = NothingEnd Function18.使用FSO读取文件某一行的函数function FSOlinedit(filename,lineNum)if linenum < 1 then exit functiondim fso,f,temparray,tempcntset fso = server.CreateObject("scripting.filesystemobject")if not fso.fileExists(server.mappath(filename)) then exit functionset f = fso.opentextfile(server.mappath(filename),1)if not f.AtEndofStream thentempcnt = f.readallf.closeset f = nothingtemparray = split(tempcnt,chr(13)&chr(10))if lineNum>ubound(temparray)+1 thenexit functionelseFSOlinedit = temparray(lineNum-1)end ifend ifend function19.使用FSO写文件某一行的函数function FSOlinewrite(filename,lineNum,Linecontent)if linenum < 1 then exit functiondim fso,f,temparray,tempCntset fso = server.CreateObject("scripting.filesystemobject")if not fso.fileExists(server.mappath(filename)) then exit function set f = fso.opentextfile(server.mappath(filename),1)if not f.AtEndofStream thentempcnt = f.readallf.closetemparray = split(tempcnt,chr(13)&chr(10))if lineNum>ubound(temparray)+1 thenexit functionelsetemparray(lineNum-1) = lineContentend iftempcnt = join(temparray,chr(13)&chr(10))set f = fso.createtextfile(server.mappath(filename),true)f.write tempcntend iff.closeset f = nothingend function20.使用FSO添加文件新行的函数function FSOappline(filename,Linecontent)dim fso,fset fso = server.CreateObject("scripting.filesystemobject")if not fso.fileExists(server.mappath(filename)) then exit function set f = fso.opentextfile(server.mappath(filename),8,1)f.write chr(13)&chr(10)&Linecontentf.closeset f = nothingend function21.读文件最后一行的函数function FSOlastline(filename)dim fso,f,temparray,tempcntset fso = server.CreateObject("scripting.filesystemobject")if not fso.fileExists(server.mappath(filename)) then exit function set f = fso.opentextfile(server.mappath(filename),1)if not f.AtEndofStream thentempcnt = f.readallf.closeset f = nothingtemparray = split(tempcnt,chr(13)&chr(10))FSOlastline = temparray(ubound(temparray))end ifend function。

相关文档
最新文档