常用第三方控件
添加第三方控件
在工具箱任意一个选项卡中单击右键——再单击选择项——在选择工具箱项中的.NET Framework 组建中——单击浏览——在弹出的对话框中查找要添加的第三方控件——单击打开——最后单击确定使用FreeTextBox在线编辑录入控件
1、添加FreeTextBox到标准工具箱——在页面中添加FreeTextBox控件即可
2、FreeTextBox控件常用属性
3、设置FreeTextBox控件Text属性实现绑定数据(必须使用Bind进行数据绑定,如果使用Eval将无法完成目录的更新)例:
<FTB:FreeTextBox---ID="FreeTextBox1"--runat="server"--Text='<%#Bind("Name")%>'></FTB:FreeTextBox>
4、错误处理
错误提示:从客户端中检测到有潜在危险的Request.From 值
错误原因:这是由于Asp.Net自身安全机制引起的,它屏蔽了有潜在危险的表单提交。
解决方法:在Page指令上设置ValidateRquest="false" 就可以了
使用验证码控件
1、添加SerialNumber控件到标准工具箱——在页面中添加SerialNumber控件
2、在后置代码中编辑验证代码
//首次加载处理
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack) {
this.SerialNumber1.Create(); //首次加载页面创建新验证码
}}
//判断输入的验证码是否正确,并做出相应的显示
protected void Button1_Click(object sender, EventArgs e){
if (SerialNumber1.CheckSN(this.TextBox1.Text.Trim()))
{ this.Label1.Text = "<script>alert('正确!');</script>";
} else {
SerialNumber1.Create();
}}
常用属性和方法 |
||
返回类型 |
方法名 |
说明 |
void |
Create() |
创建新验证码 |
bool |
CheckSN(比较参数) |
验证输入的验证码是否正确 |
session 生成验证码
1、编写生成的验证码页面(GenerateSureCode.aspx)
using System;using System.Data;using System.Configuration;using System.Collections;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.Drawing;
public partial class GenerateSureCode : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
this.GenImg(this.GenCode(4));
} }
//产生随机字符串
private string GenCode(int num) {
string[] source ={"0","1","2","3","4","5","6","7","8","9",
"A","B","C","D","E","F","G","H","I","J","K","L","M","N",
"O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
string code = "";
Random rd = new Random();
for (int i = 0; i < num; i++) {
code += source[rd.Next(0, source.Length)];
}
return code; }
//生成图片
private void GenImg(string code) {
Bitmap myPalette = new Bitmap(60, 20);//定义一个画板
Graphics gh = Graphics.FromImage(myPalette);//在画板上定义绘图的实例
Rectangle rc = new Rectangle(0, 0, 60, 20);//定义一个矩形
gh.FillRectangle(new SolidBrush(Color.Yellow), rc);//填充矩形
gh.DrawString(code, new Font("宋体", 16), new SolidBrush(Color.Red), rc);//在矩形内画出字符串
myPalette.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//将图片显示出来
Session["ValidateCode"] = code;//将字符串保存到Session中,以便需要时进行验证
gh.Dispose(); myPalette.Dispose();
} }
2在页面中加一个Image图片控件(通过ImageUrl属性获得在GenerateSureCode.aspx页面生成的验证码)
<asp:Image ID="imgValidate" ImageUrl="~/GenerateSureCode.aspx" runat="server" />
3、在后置代码中编写如下代码
//此方法验证用户输入的验证码是否与生成的验证码一样
private bool CheckSN() {
string validateCode = Session["ValidateCode"].ToString();//获得保存在Session中的验证码
if (this.txtValidate.Text != validateCode) {
Response.Write("<script>alert('验证码输入错误,请重新输入!');</script>");
txtValidate.Text = "";
return false;
} else {
return true;
} }