c# - 带有 Html 内容占位符的 ASP.NET 通用用户控件

标签 c# jquery asp.net

这个问题可能已经被问过,但我找不到任何引用资料,所以如果它看起来像是一个重复的问题,我深表歉意。

我想做的是创建一个通用的 DialogBox作为 ASP.NET 用户控件;它将包含使用 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 内容占位符,它可以绑定(bind)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 通用用户控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25649207/

相关文章:

jquery - 如何在 typeahead 函数调用中使用 bootstrap 的 typeahead 获取文本框的属性

Asp.net电子商务性能

asp.net - 在 Web 和非 Web 应用程序之间共享 HttpContext 代码

c# - Getting The query contains references do Elements defined in the context of other data 错误

c# - 最快的类型比较?

c# - 为什么我需要用 EntryPoint 属性定义 DLLImport

ASP.NET Web API - 不允许使用 PUT 和 DELETE 动词 - IIS 8

c# - 单元测试Elastic Search Nest客户端-BulkAll

javascript - 使用 JQuery 和数据属性进行多重过滤

javascript - data-ng-options 中的自定义 html 内容