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

时间:2012-08-27 21:07:23

标签: javascript asp.net

我有一个带复选框控件的自定义覆盖文本框。控件工作正常,除非我尝试在Javascript中引用Control的TextBox / CheckBox ID然后在呈现控件之前得到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);
    }

1 个答案:

答案 0 :(得分:0)

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