zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

asp.netajax实现无刷新验证码

ASP 实现 刷新 验证码 netajax
2023-06-13 09:14:30 时间
1、首先是在后台验证码的aspx文件的Page_Load中的事件代码:
复制代码代码如下:

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Drawing;
namespace学生在线考试系统
{
publicpartialclassAjaxAutoCode:System.Web.UI.Page
{
//验证数字
publicstringauthcode=string.Empty;
protectedvoidPage_Load(objectsender,EventArgse)
{
#region第一种产生验证码的方法
Randomrandom=newRandom();
authcode=random.Next(1111,9999).ToString();
//构造图片
Bitmapimage=newBitmap(authcode.Length*12,25);
//创建画布
Graphicsg=Graphics.FromImage(image);
try
{
g.Clear(Color.White);
for(inti=0;i<25;i++)
{
intx1=random.Next(image.Width);
intx2=random.Next(image.Width);
inty1=random.Next(image.Height);
inty2=random.Next(image.Height);
//链接两点的线条
g.DrawLine(newPen(Color.Silver),x1,y1,x2,y2);
}
Fontfont=newFont("Arial",12,FontStyle.Bold|FontStyle.Italic);
System.Drawing.Drawing2D.LinearGradientBrushbrush=newSystem.Drawing.Drawing2D.LinearGradientBrush(
newRectangle(0,0,image.Width,image.Height),Color.Blue,Color.DarkBlue,1.2f,true);
g.DrawString(authcode,font,brush,2,2);
//画图片的前景噪点
for(inti=0;i<100;i++)
{
intx=random.Next(image.Width);
inty=random.Next(image.Height);
image.SetPixel(x,y,Color.FromArgb(random.Next()));
}
g.DrawRectangle(newPen(Color.Silver),0,0,image.Width-1,image.Height-1);
System.IO.MemoryStreamms=newSystem.IO.MemoryStream();
image.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
ms.WriteTo(this.Response.OutputStream);
ms.Close();
this.Response.ContentType="image/gif";
}
finally
{
image.Dispose();
g.Dispose();
}
#endregion
}
}
}

2、其次在显示验证码的页面定义一个JS函数
复制代码代码如下:

functionfGetCode()
{
document.getElementById("getcode").src="Default2.aspx?"+Math.random();
}

3.再编辑前台页面aspx,下面是前台页面的代码片段
复制代码代码如下:
<label>验证码</label>
<asp:TextBoxID="txt_checkCode"runat="server"Width="178px"></asp:TextBox>
<imgsrc="Default2.aspx"alt="看不清楚?"id="getcode"/><ahref="javascript:fGetCode()">更换验证码</a>