CreateUserWizard控件

在ASP.NET中,制作登录和用户信息最快捷的方式就是使用Membership,Role,Profile provide. 在使用他们的过程中,一般情况下需要在注册界面加上验证码功能来防止有人利用机器人之类的软件自动批量注册,

而这里将介绍怎样使用CreateUserWizard控件去做一个简单注册界面,当然你需要使用自己的数据表和其他功能的话,可以在这个sample上面添加,本samples实现了一些最基本的功能。

 

这个应用程序使用了CreateUserWizard的CreateUserWizardStep和CompleteWizardStep template来收集用户信息,并且添加验证码控件。同时,这里需要使用Sqlserver创建MDF的文件,所以你需要安装一个数据 库,express版本的即可,这里是官方下载地址:

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=8b3695d9-415e-41f0-a079-25ab0412424b&displaylang=en

 

新建一个项目 ASP.NET Empty Web Application, 添加一个Web form, 命名为“Default.aspx”. 在aspx界面上创建一个CreateUserWizard控件,并且添加你想要的注册信息,本例的代码如下:

 

Default.aspx

 

[c-sharp] view plaincopy
  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head runat="server">  
  3.     <title></title>  
  4. </head>  
  5. <body>  
  6.     <form id="form1" runat="server">  
  7.     <div>  
  8.     <asp:CreateUserWizard ID="CreateUserWizardName" runat="server"    
  9.             onnextbuttonclick="CreateUserWizardName_NextButtonClick"   
  10.             oncreatinguser="CreateUserWizardName_CreatingUser">   
  11.             <WizardSteps>   
  12.                 <asp:CreateUserWizardStep ID="CreateUserWizardNameStep" runat="server">   
  13.                     <ContentTemplate>   
  14.                         <table border="0" style="font-size: 100%; font-family: Verdana" mce_style="font-size: 100%; font-family: Verdana">   
  15.                             <tr>   
  16.                                 <td align="center" colspan="2" style="font-weight: bold; color: white; background-color: #5d7b9d" mce_style="font-weight: bold; color: white; background-color: #5d7b9d">   
  17.                                     Sign Up for Your New Account   
  18.                                 </td>   
  19.                             </tr>                  
  20.                             <tr>   
  21.                                 <td align="right">  
  22.                                     <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">   
  23.                         User Name:</asp:Label>  
  24.                                 </td>  
  25.                                 <td>  
  26.                                     <asp:TextBox ID="UserName" runat="server"></asp:TextBox>  
  27.                                     <asp:RequiredFieldValidator ID="UserNameRequired" runat="server"   
  28.                                         ControlToValidate="UserName" ErrorMessage="User Name is required."   
  29.                                         ToolTip="User Name is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>  
  30.                                 </td>  
  31.                             </tr>  
  32.                             <tr>  
  33.                                 <td align="right">  
  34.                                     <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">   
  35.                         Password:</asp:Label>  
  36.                                 </td>  
  37.                                 <td>  
  38.                                     <asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>  
  39.                                     <asp:RequiredFieldValidator ID="PasswordRequired" runat="server"   
  40.                                         ControlToValidate="Password" ErrorMessage="Password is required."   
  41.                                         ToolTip="Password is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>  
  42.                                 </td>  
  43.                             </tr>  
  44.                             <tr>  
  45.                                 <td align="right">  
  46.                                     <asp:Label ID="ConfirmPasswordLabel" runat="server"   
  47.                                         AssociatedControlID="ConfirmPassword">   
  48.                         Confirm Password:</asp:Label>  
  49.                                 </td>  
  50.                                 <td>  
  51.                                     <asp:TextBox ID="ConfirmPassword" runat="server" TextMode="Password"></asp:TextBox>  
  52.                                     <asp:RequiredFieldValidator ID="ConfirmPasswordRequired" runat="server"   
  53.                                         ControlToValidate="ConfirmPassword"   
  54.                                         ErrorMessage="Confirm Password is required."   
  55.                                         ToolTip="Confirm Password is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>  
  56.                                 </td>  
  57.                             </tr>  
  58.                             <tr>  
  59.                                 <td align="right">  
  60.                                     <asp:Label ID="EmailLabel" runat="server" AssociatedControlID="Email">   
  61.                         E-mail:</asp:Label>  
  62.                                 </td>  
  63.                                 <td>  
  64.                                     <asp:TextBox ID="Email" runat="server"></asp:TextBox>  
  65.                                     <asp:RequiredFieldValidator ID="EmailRequired" runat="server"   
  66.                                         ControlToValidate="Email" ErrorMessage="E-mail is required."   
  67.                                         ToolTip="E-mail is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>  
  68.                                 </td>  
  69.                             </tr>  
  70.                             <tr>  
  71.                                 <td align="right">  
  72.                                     <asp:Label ID="QuestionLabel" runat="server" AssociatedControlID="Question">   
  73.                         Security Question:</asp:Label>  
  74.                                 </td>  
  75.                                 <td>  
  76.                                     <asp:TextBox ID="Question" runat="server"></asp:TextBox>  
  77.                                     <asp:RequiredFieldValidator ID="QuestionRequired" runat="server"   
  78.                                         ControlToValidate="Question" ErrorMessage="Security question is required."   
  79.                                         ToolTip="Security question is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>  
  80.                                 </td>  
  81.                             </tr>  
  82.                             <tr>  
  83.                                 <td align="right">  
  84.                                     <asp:Label ID="AnswerLabel" runat="server" AssociatedControlID="Answer">   
  85.                         Security Answer:</asp:Label>  
  86.                                 </td>  
  87.                                 <td>  
  88.                                     <asp:TextBox ID="Answer" runat="server"></asp:TextBox>  
  89.                                     <asp:RequiredFieldValidator ID="AnswerRequired" runat="server"   
  90.                                         ControlToValidate="Answer" ErrorMessage="Security answer is required."   
  91.                                         ToolTip="Security answer is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>  
  92.                                 </td>  
  93.                             </tr>  
  94.                              <tr>   
  95.                                 <td align="right">   
  96.                                     <asp:Label ID="lblCaptcha" runat="server" AssociatedControlID="codeNumberTextBox">   
  97.                         Code Number:</asp:Label>   
  98.                                 </td>   
  99.                                 <td>   
  100.                                     <asp:TextBox ID="codeNumberTextBox" runat="server"></asp:TextBox><asp:Label ID="lbMessage"   
  101.                                         runat="server" Text="Label"></asp:Label>   
  102.                                     <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="UserName"   
  103.                                         ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>   
  104.                                 </td>   
  105.                             </tr>  
  106.                             <tr>  
  107.                                 <td align="center" colspan="2">  
  108.                                     <asp:CompareValidator ID="PasswordCompare" runat="server"   
  109.                                         ControlToCompare="Password" ControlToValidate="ConfirmPassword"   
  110.                                         Display="Dynamic"   
  111.                                         ErrorMessage="The Password and Confirmation Password must match."   
  112.                                         ValidationGroup="CreateUserWizard1"></asp:CompareValidator>  
  113.                                 </td>  
  114.                             </tr>  
  115.                             <tr>  
  116.                                 <td align="center" colspan="2" style="color: red" mce_style="color: red">  
  117.                                     <asp:Literal ID="ErrorMessage" runat="server" EnableViewState="False"></asp:Literal>  
  118.                                 </td>  
  119.                             </tr>  
  120.                         </table>   
  121.                     </ContentTemplate>   
  122.                 </asp:CreateUserWizardStep>   
  123.                 <asp:CompleteWizardStep ID="CreateUserWizardComplete" runat="server">  
  124.                 <ContentTemplate>  
  125.                 <center><asp:Label ID="lbTitle" runat="server" Text="Personal Information"></asp:Label></center><br />  
  126.                 User Name:  <asp:Label ID="lbUserName" runat="server"></asp:Label><br />  
  127.                 E-mail:  <asp:Label ID="lbEmail" runat="server"></asp:Label><br />  
  128.                 Question:  <asp:Label ID="lbQuestion" runat="server"></asp:Label><br />  
  129.                 </ContentTemplate>  
  130.                 </asp:CompleteWizardStep>   
  131.             </WizardSteps>   
  132.         </asp:CreateUserWizard>   
  133.         <asp:Label ID="lbError" runat="server" Font-Bold="True"></asp:Label>  
  134.     </div>   
  135.     </form>  
  136. </body>  
  137. </html>  

 

这里的CreateUserWizardStep中显示的是最初看到的内容,而CompleteWizardStep显示的是点击创建用户完了看到的内容,比较简单

 

第二步 添加后台代码了, 首先我们要写一个生成随机数和字母的方法,用来生成随机代码,这里只是作为一个label的Text属性来显示,不安全,你可以把他生成为一张图片来显示(通过使用Graphics类)。有一个贴子,大家可以参考:

http://blog.csdn.net/21aspnet/archive/2007/03/20/1534392.aspx

 

生成随机数的方法GenerateRandomCode(),添加到Default.aspx.cs界面

[c-sharp] view plaincopy
  1. // Used to create numbers randomly   
  2. private string GenerateRandomCode()  
  3. {  
  4.     string allChar = "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";  
  5.     int codeCount = 6;  
  6.     string[] allCharArray = allChar.Split('','');  
  7.     string randomCode = "";  
  8.     int temp = -1;  
  9.   
  10.     Random rand = new Random();  
  11.     for (int i = 0; i < codeCount; i++)  
  12.     {  
  13.         if (temp != -1)  
  14.         {  
  15.             rand = new Random(i * temp * ((int)DateTime.Now.Ticks));  
  16.         }  
  17.         int t = rand.Next(allCharArray.Length - 1);  
  18.         if (temp == t)  
  19.         {  
  20.             return GenerateRandomCode();  
  21.         }  
  22.         temp = t;  
  23.         randomCode += allCharArray[t];  
  24.     }  
  25.   
  26.     // Set value to session variable when the function is called.   
  27.     Session["CaptchaImageText"] = randomCode;  
  28.     return randomCode;  
  29. }  

  

 

 

第三步,把下列代码添加到Default.aspx.cs页面的page_load事件中,这里比较简单,在第一次加载页面时生成验证码,同时定义了一个私有bool变量IsCreateSuc,在后面会用到
 
Page_Load事件代码(Default.aspx.cs) 

 

[c-sharp] view plaincopy
  1. private bool IsCreateSuc;  
  2.         protected void Page_Load(object sender, EventArgs e)  
  3.         {  
  4.             // Get label from CreateUserWizard control.  
  5.             Control ctrllbl = CreateUserWizardName.CreateUserStep.ContentTemplateContainer.FindControl("lbMessage");  
  6.             if (ctrllbl != null)  
  7.             {  
  8.                 if (!IsPostBack)  
  9.                 {  
  10.                     Label lbl = (Label)ctrllbl;  
  11.                     string captchaCode = GenerateRandomCode();  
  12.                     this.Session["CaptchaImageText"] = captchaCode;  
  13.                     lbl.Text = captchaCode;  
  14.                 }  
  15.             }  
  16.         }  

 

最后一步了,调用CreateUserWizard控件的两个方法NextButtonClick和CreatingUser,我使用的是vs2010开发,其他版本的vs不知道名称是否都一致,详细名称可以查询下MSDN。

 

这里CreateingUser事件,在创建新用户的时候触发,在这个事件中你可以添加自己的判断代码,比如这里就用到了验证我们生成的验证码是否 和输入的匹配,如果不匹配,使用e.Cancal=true来取消创建用户的sql command, 如果你使用之后事件来写取消创建用户这个步骤是不行的(例如CreatedUser和NextButtonClick)。

例如:你把判断验证码的代码写在了NextButtonClick,也使用e.Cancal=true来返回,那么你也可以看到应用程序返回错误信息,但是在数据库中新用户创建成功了。

 

所以我们在CreateingUser事件中判断验证码是否匹配,并且传给私有的信号变量IsCreateSuc,通知下一步的事件返回成功信息,或者是保持在注册页面。

 

 

CreatingUser事件代码。(Default.aspx.cs)

 

[c-sharp] view plaincopy
  1.  /// <summary>  
  2. /// Check the captcha code is matched.  
  3. /// </summary>  
  4. /// <param name="sender"></param>  
  5. /// <param name="e"></param>  
  6. protected void CreateUserWizardName_CreatingUser(object sender, LoginCancelEventArgs e)  
  7. {  
  8.     Control ctrl = CreateUserWizardName.CreateUserStep.ContentTemplateContainer.FindControl("codeNumberTextBox");  
  9.     TextBox txb = (TextBox)ctrl;  
  10.     // You can check the user input like this:   
  11.     if (txb.Text == this.Session["CaptchaImageText"].ToString())  
  12.     {  
  13.         this.IsCreateSuc = true;            
  14.     }  
  15.     else  
  16.     {  
  17.         this.IsCreateSuc = false;  
  18.         lbError.Text = "ERROR: Captcha code incorrect, please try again.";  
  19.         txb.Text = "";  
  20.         e.Cancel = true;  
  21.     }  
  22. }   

 

 

NextButtonClick事件代码。(Default.aspx.cs)

[c-sharp] view plaincopy
  1. /// <summary>  
  2. /// After create a user account, display user''s basic information.  
  3. /// </summary>  
  4. /// <param name="sender"></param>  
  5. /// <param name="e"></param>  
  6. protected void CreateUserWizardName_NextButtonClick(object sender, WizardNavigationEventArgs e)  
  7. {  
  8.     if (IsCreateSuc)  
  9.     {  
  10.         // Display an informational message  
  11.         lbError.Text = "Create a new user";  
  12.         // Display your information  
  13.         Control ctrlName = CreateUserWizardName.CreateUserStep.ContentTemplateContainer.FindControl("UserName");  
  14.         string strUserName = ((TextBox)ctrlName).Text;  
  15.         Control ctrlPassword = CreateUserWizardName.CreateUserStep.ContentTemplateContainer.FindControl("Password");  
  16.         string strPassword = ((TextBox)ctrlPassword).Text;  
  17.         Control ctrlLbUsername = CreateUserWizardName.CompleteStep.ContentTemplateContainer.FindControl("lbUserName");  
  18.         Control ctrlLbEmail = CreateUserWizardName.CompleteStep.ContentTemplateContainer.FindControl("lbEmail");  
  19.         Control ctrlLbQuestion = CreateUserWizardName.CompleteStep.ContentTemplateContainer.FindControl("lbQuestion");  
  20.         MembershipUser userInfo;  
  21.         if (Membership.ValidateUser(strUserName, strPassword) == true)  
  22.         {  
  23.             userInfo = Membership.GetUser(strUserName);  
  24.             ((Label)ctrlLbUsername).Text = userInfo.UserName;  
  25.             ((Label)ctrlLbQuestion).Text = userInfo.PasswordQuestion;  
  26.             ((Label)ctrlLbEmail).Text = userInfo.Email;  
  27.         }  
  28.     }  
  29.     else  
  30.     {  
  31.         e.Cancel = true;  
  32.     }  
  33. }  

 

 

 

 

好了,那么你可以开始运行项目了。注意,第一次注册可能会比较慢,因为应用程序要在你的项目中创建一个db file。默认名字是ASPNETDB.MDF, 创建用户成功后, 会显示账户的基本信息.

posted @ 2013-03-11 14:38  天涯海角路  阅读(753)  评论(0)    收藏  举报