使用验证控件(Validator)验证用户控件(UserControl)的解决方案
在asp.net中,默认情况下,验证控件(RequiredFieldValidator,CustomValidator,etc)是不能验自定义的用户控件(UserControl的.
那么,如何用户控件被验证控件所使用呢? 方法有二:
1) 创建自定义的Validator; (参考:http://www.dotnetcurry.com/ShowArticle.aspx?ID=197)
此方法太过复杂,而且范例在UpdatePanel中无法使用.(javascript没有成功render到页面上)
2) 创建能够为验证控件所直接调用的用户控件;
此方法需要三个步骤:a)用ValidationPropertyAttribute修改用户控件类; b)在Render()方法中用一个div将所有内容包括在内.
示例代码:
1
2 using System.Web;
3 using System.Web.UI;
4 using System.Web.UI.WebControls;
5
6 namespace AdminTrack.Event.UC
7 {
8 [ValidationProperty("Value"), SupportsEventValidation]
9 public partial class RadioBtn : System.Web.UI.UserControl
10 {
11 // render a div as wrapper to include all contents in user control
12 protected override void Render(HtmlTextWriter writer)
13 {
14 writer.WriteBeginTag("div");
15 writer.WriteAttribute("id", this.ClientID);
16 writer.Write('>');
17
18 base.Render(writer);
19
20 writer.WriteEndTag("div");
21 }
22 // the property to validate
23 public string Value { get; set; }
24 }
25 }
3 using System.Web.UI;
4 using System.Web.UI.WebControls;
5
6 namespace AdminTrack.Event.UC
7 {
8 [ValidationProperty("Value"), SupportsEventValidation]
9 public partial class RadioBtn : System.Web.UI.UserControl
10 {
11 // render a div as wrapper to include all contents in user control
12 protected override void Render(HtmlTextWriter writer)
13 {
14 writer.WriteBeginTag("div");
15 writer.WriteAttribute("id", this.ClientID);
16 writer.Write('>');
17
18 base.Render(writer);
19
20 writer.WriteEndTag("div");
21 }
22 // the property to validate
23 public string Value { get; set; }
24 }
25 }