在web开发中,我们通常会将重复使用的代码分装成UserControl,方便之后reuse,例如DateTime控件、HtmlEditor等。

MS为asp.net 提供了一种简单的验证机制。本文要说的重点就是讲这种验证用在用户控件中。

 

要让用户控件可以被验证,只需要为控件的类添加一个特性:[ValidationProperty("SelectID")],例如:

    [ValidationProperty("SelectID")]
public partial class TextBoxAutoComplete : System.Web.UI.UserControl
{
#region 属性

/// <summary>
/// 从AutoComplete中选择的ID
/// </summary>
public string SelectID
{
get
{
return this.AutoComplete_Hidden.Value;
}
set
{
this.AutoComplete_Hidden.Value = value;
}
}

#endregion

#region 页面加载

protected void Page_Load(object sender, EventArgs e)
{

}

#endregion
}


这样虽然可以验证,但是,你会发现每次都会回发到服务器端进行验证,使用Page.IsValid,很不方便!貌似是因为不支持Client Script的验证,那么怎样才可以在客户端完成验证呢?

答案便是需要在客户端注册一个隐藏域,ID与控件的ClientID相同,同时需要在客户端更新后用脚本更新这个字段的值。

    [ValidationProperty("SelectID")]
public partial class TextBoxAutoComplete : System.Web.UI.UserControl
{
#region 属性

/// <summary>
/// 从AutoComplete中选择的ID
/// </summary>
public string SelectID
{
get
{
return this.AutoComplete_Hidden.Value;
}
set
{
this.AutoComplete_Hidden.Value = value;
}
}

#endregion

#region 页面加载

protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterHiddenField(this.ClientID, this.SelectID);  //注意此句代码,同时需要向客户端添加事件,此处略过
}

#endregion
}


以上的内容便可以完成客户端验证了。

相关文章:

  • 2022-12-23
  • 2021-06-06
  • 2021-09-14
  • 2022-02-05
  • 2021-09-23
  • 2022-12-23
  • 2021-09-01
  • 2021-07-28
猜你喜欢
  • 2021-11-09
  • 2021-06-23
  • 2022-02-10
  • 2022-03-11
  • 2021-07-09
  • 2021-08-21
相关资源
相似解决方案