【问题标题】:integrate custom control controls validation with Page.IsValid将自定义控件控件验证与 Page.IsValid 集成
【发布时间】:2011-09-29 12:38:17
【问题描述】:

我创建了一个自定义服务器控件。到目前为止,此控件在网页中呈现了一些 html。在提交页面时,我需要获取在服务器控件的文本框中输入的值并调用一些 Web 服务来验证用户的输入。我不想在使用此控件的页面后面的代码中编写此代码。我希望将所有验证写入服务器控件本身,如果验证失败,Page.IsValid 应设置为 false。如果服务器控件中的用户输入值是有效的 Page.IsValid 将为真。

我正在尝试实现与 google recaptcha 相同的功能。用户使用该控件所需要做的就是在页面中使用该控件。用户输入的值正确或不正确在控件本身和页面后面的代码中处理,只有Page.IsValid。这是谷歌上解释这一点的页面

http://code.google.com/apis/recaptcha/docs/aspnet.html

我也使用了 google recaptcha,它按预期工作。我还想为我的服务器控件构建相同类型的功能,如果可能,请提供帮助。

【问题讨论】:

    标签: asp.net validation controls


    【解决方案1】:

    感谢您回答问题。我找到了解决方案。这是服务器控件的完整代码。诀窍是实现 IValidator。它给了我们两个属性和一个方法。 ErrorMessage 和 IsValid 属性和 Validate 方法。我在Validate方法中编写了所有验证代码并设置了this.IsValid。这样就解决了问题。

    [ToolboxData("<{0}:MyControl runat=server></{0}:MyControl>")]
    public class MyControl : WebControl, IValidator
    {
        protected override void RenderContents(HtmlTextWriter output)
        {
            //Render the required html
        }
    
        protected override void Render(HtmlTextWriter writer)
        {
            this.RenderContents(writer);
        }
    
        protected override void OnInit(EventArgs e)
        {
            Page.Validators.Add(this);
            base.OnInit(e);
        }
    
        public string ErrorMessage
        {
            get;
            set;
        }
    
        public bool IsValid
        {
            get;
            set;
        }
    
        public void Validate()
        {
            string code = Context.Request["txtCode"];
            this.IsValid = Validate(code);//this method calls the webservice and returns true or false
            if (!this.IsValid)
            {
                ErrorMessage = "Invalid Code";
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以将验证器合并到服务器控件中。它需要一个服务器验证方法来调用 Web 服务。

      最终结果将是您将服务器控件放在页面上,不需要其他验证器。如果您的控件无法验证其内容,则 page.isvalid 将为 false。

      西蒙

      【讨论】:

      • simon,我的服务器控件不呈现任何服务器端控件。它只呈现 html 文本框和一些隐藏字段。我使用请求变量获取用户输入,然后对其进行验证。能否请您详细说明您的方法。
      • 您的解决方案或多或少符合我的建议,但可能是更好的解决方案,因为您没有使用任何服务器控件。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多