Asp.net ScriptManager.RegisterStartupScript失败,错误为“0”;控件必须位于页面的控件树中。参数名称:control";

Asp.net ScriptManager.RegisterStartupScript失败,错误为“0”;控件必须位于页面的控件树中。参数名称:control";,asp.net,Asp.net,我正在创建一个自定义web控件,基本上扩展了RadTextBox,因为它没有onBlur()事件。我在.ascx文件中添加了一个脚本。我正在尝试注册脚本,但失败了。我不确定我错过了什么 <script language="javascript"> function handleLostFocus(o) { aler(o.toString()); } </script> public partial class MyTextBox : Ra

我正在创建一个自定义web控件,基本上扩展了RadTextBox,因为它没有onBlur()事件。我在.ascx文件中添加了一个脚本。我正在尝试注册脚本,但失败了。我不确定我错过了什么

<script language="javascript">
    function handleLostFocus(o) {
        aler(o.toString());
    }
</script>

public partial class MyTextBox : RadTextBox, IScriptControl
{
    private void RegisterScripts()
    {
        try
        {
            String csname1 = "handleLostFocus";
            Type cstype = this.GetType();

            String cstext1 = "alert('Hello World');";
            ScriptManager.RegisterStartupScript(this, cstype, csname1, cstext1, true);
        }
        catch (Exception ex)
        {

        }
    }

    public MyTextBox()
    {
        Attributes.Add("padding", "5px");
        Skin = "Office2007";
        Attributes.Add("onBlur", "handleLostFocus(this);");

        RegisterScripts();
    }
}

函数handleLostFocus(o){
aler(o.toString());
}
公共部分类MyTextBox:RadTextBox,IScriptControl
{
私有无效注册表脚本()
{
尝试
{
字符串csname1=“handleLostFocus”;
类型cstype=this.GetType();
字符串cstext1=“警报('Hello World');”;
RegisterStartupScript(this,cstype,csname1,cstext1,true);
}
捕获(例外情况除外)
{
}
}
公共MyTextBox()
{
添加(“填充”、“5px”);
Skin=“Office2007”;
添加(“onBlur”、“handleLostFocus(this);”;
RegisterScripts();
}
}

您正在类的构造函数中调用RegisterScript。您的控件尚未在构造函数的页中,因此您无法为尚未在页中的控件注册启动脚本

我认为最好的方法是Init方法。可以通过将构造函数中的调用替换为以下内容来完成此操作:

Init+=(s,e)=>{RegisterScripts();}


(您也可以在控件上创建一个完整的Init方法,但这是一个简写版本)

Wow,它现在注册了脚本。但它会立即调用该函数,我只需要在onBlur()上调用它。RegisterStartupScript会注册一个脚本以在启动时运行。。。以这种方式注册的任何脚本都将在应用程序启动后立即运行。提供的名称是.NET使用的标识符,而不是要声明的javascript函数的名称。如果要声明名为“handleLostFocus”的函数,则需要cstext1来包含整个函数声明(例如:
cstext1=“function handleLostFocus(){alert('Hello World');}”;