C#自定义控件将内部文本作为字符串

时间:2010-05-20 08:59:09

标签: c# asp.net custom-controls

好的,我正在开发一个可以包含一些javascript的自定义控件,并将其从页面中读取到字符串字段中。

这是更新面板内动态JavaScript的解决方法。

目前,我已经开始工作了,但是如果我尝试在服务器标签中放置一个服务器标签:

<custom:control ID="Custom" runat="server">
    <%= ControlName.ClientID %>
</custom:control>

编译器不喜欢它。我知道这些都是在运行时生成的,因此可能与我正在做的事情不兼容,但有没有人知道我如何才能使它工作?

修改

错误消息是:此上下文不支持代码块

编辑2

控件:

[DataBindingHandler("System.Web.UI.Design.TextDataBindingHandler, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), ControlValueProperty("Text"), DefaultProperty("Text"), ParseChildren(true, "Text"), AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal), AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public class CustomControl : Control, ITextControl
{
    [DefaultValue(""), Bindable(true), Localizable(true)]
    public string Text
    {
        get
        {
            return (string)(ViewState["Text"] ?? string.Empty);
        }

        set
        {
            ViewState["Text"] = value;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

编译器是写入的,服务器端代码块仅在ITemplate的上下文中受支持。

“Text”属性应该像这样设置......

<custom:control ID="Custom" runat="server" Text="YourText">

使用ITemplate,你可以在代码隐藏中声明它......

public ITemplate Text
{
    get;
    set;
}

但是你需要这样做......

<custom:control ID="Custom" runat="server">
   <Text><%= ControlName.ClientID %></Text>
</custom:control>

话虽如此,如果您有自定义控件,为什么不在后面的代码中执行此操作...

this.text = ((ITextControl)Page.FindControl(controlName)).Text;

麻烦的是,它不是很有活力。

我赞成模板化选项。 虽然难以实施。