【问题标题】:Appending to div with specific class附加到具有特定类的 div
【发布时间】:2018-04-08 04:00:41
【问题描述】:

如何将一些 html 附加到具有特定类名的 div 中?

前端:

<div class="school-team-popup"></div>

后端:

StringBuilder _html = new StringBuilder();

_html.AppendFormat("<li>Hi there</li>");

我想在 school-team-popup div 中附加 _html。如何从后端执行此操作?

【问题讨论】:

  • 这是什么? ASP.NET Web 窗体? MVC? MVC 核心?南希?
  • 是的 .NET 网络表单
  • 那您为什么要手动构建 HTML 并尝试将其添加到您的表单中?为什么不直接在标记中声明,通过设置控件的Visible属性来控制它是否出现在页面上呢?
  • 该示例显示我附加了静态 html,但实际上我将从服务器中提取动态数据以进行附加。这就是我从后端做的原因
  • 手动构建 HTML 并不是 Web 表单的工作方式。如果您在后端提取数据并希望将其显示在页面上,则通常将该数据绑定到控件。

标签: c# html asp.net webforms


【解决方案1】:

我将解释 Web 窗体的处理方式。

如果您想在页面上选择性地显示/隐藏某些静态标记,这通常通过设置控件的 Visible 属性来完成。

<%-- This is in your ASPX markup (.aspx) --%>
<asp:Panel runat="server" id="HelloWorldPanel">
  <p>Hello, world!</p>
</asp:Panel>

//This is in your code behind (.aspx.cs)
//hide the panel
HelloWorldPanel.Visible = false;
//show the panel
HelloWorldPanel.Visible = true;

如果您尝试从其他来源获取动态数据并将其显示在页面上,则应在页面上声明标记以显示此数据,然后将数据绑定到标记。有many controls you can bind data to

可以将数据绑定到的控件的一个示例是转发器。当您想要严格控制页面上呈现的标记时,中继器非常有用。您将它们绑定到一些可枚举对象,例如 List&lt;T&gt;,然后它将为可枚举对象中的每个元素重复一些标记。

//This is in your project somewhere
namespace MyNamespace
{
    public class Product
    {
        public int Id { get; set; }

        public int Name { get; set; }
    }
}

<%-- This is in your ASPX markup (.aspx) --%>
<ul>
  <asp:Repeater runat="server" id="ProductRepeater" ItemType="MyNamespace.Product">
    <ItemTemplate>
      <li><%#: Item.Id %> - <%#: Item.Name %></li>
    </ItemTemplate>
  </asp:Repeater>
</ul>     

//this is in your code behind (.aspx.cs)
protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostback)
    {
        List<Product> products = MyDataLayer.GetProducts();
        ProductRepeater.DataSource = products;
        ProductRepeater.DataBind();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 2012-04-07
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    相关资源
    最近更新 更多