Validator.RenderControl返回一个空字符串

时间:2012-04-04 15:15:12

标签: asp.net custom-controls render

我已经面临以下问题并且与它进行了近2天的战斗。 我有以下代码。

        protected override void Render(HtmlTextWriter writer)
    {
        string controlOutput;
        string validatorOutput;
        string allOutput;
        StringWriter controlStringWriter = new StringWriter();
        HtmlTextWriter controlHtmlWriter = new HtmlTextWriter(controlStringWriter);

        StringWriter validatorsStringWriter = new StringWriter();
        HtmlTextWriter validatorsHtmlWriter = new HtmlTextWriter(validatorsStringWriter);

        base.Render(controlHtmlWriter);
        controlOutput = controlStringWriter.ToString();

        this.renderValidators(validatorsHtmlWriter);
        validatorOutput = validatorsStringWriter.ToString();

        allOutput = String.Format("{0} {1}", controlOutput, validatorOutput);
        writer.Write(allOutput);
    }

renderValidators函数是:

  private void renderValidators(HtmlTextWriter writer)
        {
            foreach (BaseValidator validator in this.ValidatorsCollection)
            {
                validator.RenderControl(writer);
            }
        }

Render Function返回一个空字符串。 集合中Validator的Visible属性设置为true。

我在OnInit函数中添加了验证器。在第一次渲染validator.RenderControl(writer)期间;返回一个空字符串,在回发后它开始返回一个html输入....

也许有人遇到过这样的问题???

1 个答案:

答案 0 :(得分:1)

根据我的理解,您需要在渲染验证器之前检查控件是否已添加到页面中。

        Page page = Page;
        if (page == null || page.Request == null) {
            return false;
        }

可以在MSDN

中找到一个非常有用的示例