asp.net ajax實現無重新整理驗證碼

來源:互聯網
上載者:User
1、首先是在後台驗證碼的aspx檔案的Page_Load中的事件代碼:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Drawing; namespace 學生線上考試系統 { public partial class AjaxAutoCode : System.Web.UI.Page { //驗證數字 public string authcode = string.Empty; protected void Page_Load(object sender, EventArgs e) { #region 第一種產生驗證碼的方法 Random random = new Random(); authcode = random.Next(1111, 9999).ToString(); //構造圖片 Bitmap image = new Bitmap(authcode.Length * 12, 25); //建立畫布 Graphics g = Graphics.FromImage(image); try { g.Clear(Color.White); for (int i = 0; i < 25; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); //連結兩點的線條 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } Font font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush( new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkBlue, 1.2f, true); g.DrawString(authcode, font, brush, 2, 2); //畫圖片的前景噪點 for (int i = 0; i < 100; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); System.IO.MemoryStream ms = new System.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函數

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

3.再編輯前台頁面aspx,下面是前台頁面的程式碼片段

<label>驗證碼</label> <asp:TextBox ID="txt_checkCode" runat="server" Width="178px"></asp:TextBox> <img src="Default2.aspx" alt="看不清楚?" id="getcode"/> <a href="javascript:fGetCode()">更換驗證碼</a>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.