可能已经有人问过这个问题,但是我找不到对此的任何引用,因此如果它看起来像是重复的问题,我深表歉意。

我正在尝试做的是将一个通用DialogBox创建为ASP.NET UserControl。其中将包含使用jQuery创建对话框所需的所有脚本。对话框具有一组固定的按钮,但是我希望能够让用户在创建对话框时定义内容。假设这是用户控件的标记:

<head>
    <script type="text/javascript">
            // jQuery script to create the dialog
    </script>
</head>
<body>
    <div runat="server" id="divContainer">
        <!--Html Content Placeholder. What goes here?-->
    </div>
</body>


和背后的代码:

[ParseChildren(true, "Contents")]
public partial class UCDialogBox : ExtendedUserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
          Page.DataBind();
    }

    public List<Control> Contents { get; set; }

    public DialogType Type { get; set; }

    public string Title { get; set; }
}


在注册控件后,在实际页面上,我希望能够执行以下操作:

<uc:DialogBox runat="server">
    <div>
        <label>Hello World</label>
    </div>
</uc:DialogBox>


问题在于,List<Control>仅允许使用ASP.NET控件。普通的HTML控件(例如我上面的控件)将无法正常工作。

问题1:我应该使用哪种类型允许任何HTML控件嵌套在用户控件内?我尝试了System.Web.UI.HtmlControls.HtmlControl,但是也没有用(ASP.NET说The element 'div' cannot be nested within the element 'dialogbox')。

问题2作为HTML内容占位符,我会将什么放置在用户控件上,该控件可以绑定到后面代码的Contents属性?就像是

<SomePlaceholderControl DataSource="<%# Contents %>" />


任何帮助表示赞赏。

最佳答案

奇怪的是,将HTML控件放入用户控件的主体内不会引起运行时错误。实际上,控件碰巧就可以了。我想这只是设计师的抱怨。

至于占位符,我不必使用任何特定控件。我只是使用HtmlTextWriter将控件呈现为在标记中调用的方法内的格式正确的HTML字符串:

<div runat="server" id="divContainer">
    <%# RenderContents() %>
</div>


以及代码隐藏方法:

public string RenderContents()
{
    StringWriter writer = new StringWriter();
    HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);

    foreach (var control in Contents)
    {
        control.RenderControl(htmlWriter);
    }

    return writer.ToString();
}


它工作正常。

关于c# - 带HTML内容占位符的ASP.NET通用UserControl,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25649207/

10-11 22:37
查看更多