LoadControl HttpCompileException自定义服务器控件JavaScript错误

LoadControl HttpCompileException Custom Server Control JavaScript Error

本文关键字:JavaScript 错误 服务器控件 自定义 HttpCompileException LoadControl      更新时间:2023-09-26

我有一个带有复选框控件的自定义覆盖文本框。除非我尝试在Javascript中引用控件的TextBox/CheckBoxID,否则控件工作正常,然后在它呈现控件之前,我会得到HttpCompileException。有没有一个重写事件更适合在一个控件中添加多个控件,或者有更好的方法完全做到这一点?

页面上的控件:OverridableTextBox runat="server"ID="otbRate"TextBoxID="txtRate"CheckBoxID="chbRate">

引用JavasScript中的ID:"<%=txtRate.ClientID%>"导致.ascx页面的LoadControl事件上出现HttpCompileException

OverrideTextBox类

    private string _TextBoxID = "";
    private string _CheckBoxID = "";
    private bool _AlignOverrideLeft = false;
    private string _CheckBoxText = "";

    public string TextBoxID
    {
        get { return _TextBoxID; }
        set { _TextBoxID = value; }
    }
    public string CheckBoxID
    {
        get { return _CheckBoxID; }
        set { _CheckBoxID = value; }
    }
    public string CheckBoxText
    {
        get { return _CheckBoxText; }
        set { _CheckBoxText = value; }
    }
    public bool AlignOverrideLeft
    {
        get { return _AlignOverrideLeft; }
        set { _AlignOverrideLeft = value; }
    }
    public TextBox TextBox = new TextBox();
    public CheckBox CheckBox = new CheckBox();
    protected override void OnInit(EventArgs e)
    {
        Table tbl = new Table();
        TableRow tr = new TableRow();
        TableCell tdOne = new TableCell();
        TableCell tdTwo = new TableCell();
        if (AlignOverrideLeft)
        {
            tdOne.Controls.Add(CheckBox);
            tdTwo.Controls.Add(TextBox);
        }
        else
        {
            tdOne.Controls.Add(TextBox);
            tdTwo.Controls.Add(CheckBox);
        }
        if (_TextBoxID != "") { TextBox.ID = _TextBoxID; }
        if (_CheckBoxID != "") { CheckBox.ID = _CheckBoxID; }
        CheckBox.Text = _CheckBoxText;
        tr.Cells.Add(tdOne);
        tr.Cells.Add(tdTwo);
        tbl.Rows.Add(tr);
        this.Controls.Add(tbl);
    }
    protected override void Render(HtmlTextWriter w)
    {
        if (CheckBox.Checked)
        {
            TextBox.ReadOnly = false;
        }
        else
        {
            TextBox.ReadOnly = true;
        }
        string CheckBoxClickJS = "var chb = d.getElementById('" + CheckBox.ClientID + "'); var txt = d.getElementById('" + TextBox.ClientID + "');";
        CheckBoxClickJS += "if (chb.checked) { EnableTextBox(txt); txt.select(); } else { DisableTextBox(txt); }";
        if (CheckBox.Attributes["onclick"] != null)
        {
            CheckBox.Attributes.Add("onclick", CheckBox.Attributes["onclick"].ToString() + CheckBoxClickJS);
        }
        else
        {
            CheckBox.Attributes.Add("onclick", CheckBoxClickJS);
        }
        base.Render(w);
    }

您的页面无法直接访问txtRate文本框,因为它位于otbRate控件的Controls集合中。请尝试以下操作:'<%= otbRate.ClientID + "_txtRate" %>'