|
欢迎来到第二部分.在写完前一部分之后我意识到如果把这些代码更模块化对你将会更有帮助.我说模块化意思是:不用每次应用都要拷贝,粘贴相同的代码.更简单 的方案是建一个继承了.net服务端控件功能的自定义控件.这不仅可使我们定制一些我们想做的事件,而且利用了被继承控件里已有的强大的功能.
我们来建立一个信用卡认证控件.首先我们需要继承Basevalidator's的功能.当然你可以自己写,但那不是一个严格意义上的自定义控件,不是吗?不仅如此而且会 占用你的很多时间.因此使用现成的东西对我们来说更划算.现在我们就开始吧. 首先,我们建个包含我们控件功能的类文件.
1: using System; 2: using System.Web.UI; 3: using System.Web.UI.WebControls; 4: 5: namespace CustomValidators 6: { 7: 8: 9: 10: 11: 12: public class CreditCardValidator : BaseValidator 13: { 14: protected override bool EvaluateIsValid() 15: { 16: 17: string valueToValidate = this.GetControlValidationValue(this.ControlToValidate); 18: int indicator = 1; 19: int firstNumToAdd = 0; 20: int secondNumToAdd = 0; 21: string num1; 22: 23: string num2; 24: 25: 26: 27: char[] ccArr = valueToValidate.ToCharArray(); 28: 29: for (int i=ccArr.Length-1;i>=0;i--) 30: { 31: char ccNoAdd = ccArr[i]; 32: int ccAdd = Int32.Parse(ccNoAdd.ToString()); 33: if (indicator == 1) 34: { 35: 36: firstNumToAdd += ccAdd; 37: 38: indicator = 0; 39: } 40: else 41: { 42: 43: 44: 45: if ((ccAdd + ccAdd) >= 10) 46: { 47: int temporary = (ccAdd + ccAdd); 48: num1 = temporary.ToString().Substring(0,1); 49: num2 = temporary.ToString().Substring(1,1); 50: secondNumToAdd += (Convert.ToInt32(num1) + Convert.ToInt32(num2)); 51: } 52: else 53: { 54: 55: secondNumToAdd += ccAdd + ccAdd; 56: } 57: 58: 59: indicator = 1; 60: } 61: } 62: 63: 64: bool isValid = false; 65: if ((firstNumToAdd + secondNumToAdd) % 10 == 0) 66: { 67: isValid = true; 68: } 69: else 70: { 71: isValid = false; 72: } 73: return isValid; 74: } 75: } 76: } 77:
| 接下来,将它保存为Validator.cs 在你的项目文件夹里.现在,为了能使用它,我们把它编译成dll.做这些你可以建一个批处理文件(.bat),也可以打开windows命令行输入以下字符:
csc /target:library /out:c:\inetpub\wwwroot\bin\Validator.dll *.cs /r:System.dll,System.Web.dll 有了dll文件你就可能使用这个控件了.随便打开一个你喜欢的编辑器,输入以下代码:
1: <%@ Register TagPrefix="custom" Namespace="CustomValidators" Assembly="Validator" %> 2: 3: <html> 4: <body> 5: <form runat="server"> 6: <asp:TextBox ID="CCNumber" Runat="server" /> 7: <custom:CreditCardValidator 8: ControlToValidate="CCNumber" 9: Runat="server" 10: ErrorMessage="Credit Card Number Invalid!" /> 11: <asp:Button Text="Validate" Runat="server" /> 12: </form> 13: </body> 14: </html>
|
保存并访问此页,输入一个测试的信用卡号码,好了,你现在已明白如何在ASP.NET中定制控件了. |
本文地址:http://com.8s8s.com/it/it45755.htm