【问题标题】:How to add text "Hello World" to WebControl like <h1>Hello World</h1>如何将文本“Hello World”添加到 WebControl,如 <h1>Hello World</h1>
【发布时间】:2014-10-11 23:09:11
【问题描述】:

需要帮助查找如何在 asp.net 中向 Web 控件添加文本。如果可能,请寻找最简单的解决方案,如果很简单,请使用控件生成器。

WebControl 生成的示例 html:

<h3>Hello World</h3>

到目前为止我的最佳尝试示例:

WebControl wc = new WebControl(HtmlTextWriterTag.H3);
wc.????

至少回答了以下两个版本:

  1. HtmlGenericControl... 可以与 var 一起使用 var h3_hgc = new HtmlGenericControl("h3"); h3_hgc.InnerText = "Hello World";

  2. LiteralControl 派生自 WebControl LiteralControl hwLiteralControl = new LiteralControl("Hello World"); wc.Controls.Add(hwLiteralControl);

【问题讨论】:

    标签: asp.net c#-4.0


    【解决方案1】:

    Headings 不是服务器 web 控件,而是 html 元素。如果需要动态创建:

    var h3 = new HtmlGenericControl("h3");
    h3.InnerHtml = "Hello World";
    container.Controls.Add(h3);
    

    其中container 是您要添加的控件。

    【讨论】:

    • InnerText 还是 InnerHtml 有关系吗?
    • 测试一下。我认为两者都有效,但只有在您使用InnerHtml(例如"Hello&lt;br&gt;World")时才会解释html。
    【解决方案2】:

    我喜欢将文字字符串放入页面的方式是使用文字标签

    默认.aspx:

    <h1><asp:Literal ID="litHeader" runat="server" /></h1>
    

    默认.aspx.cs:

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
      {
        litHeader.Text = "Hello World";
      }
    }
    

    我喜欢使用 Literal 控件的原因是没有额外的标记呈现到 HTML。每当我想在屏幕上显示任何内容但以后不会引用它来获取值时,这都很有用。

    它是如何呈现的:

    <h1>Hello World</h1>
    

    编辑:

    上面的例子是一个简单的演示方法。将任何内容输出到屏幕时,您要确保防止跨站点脚本攻击。由于您使用的是 ASP.Net Web 窗体,因此我会从 Microsoft 获得 NuGet 包“Antixss”。 (在 Server.HtmlEncode 上使用 Antixss 的 Encoder.HtmlEnocde(),heres why

    你会如何使用它:

    默认.aspx.cs:

    using Microsoft.Security.Application;
    
    protected void Page_Load(object sender, EventArgs e)
    {
      /* username is pulled from a datastore*/
      if (!IsPostBack)
      {
        litHeader.Text = Encoder.htmlEncode(username);
      }
    }
    

    【讨论】:

    • 效果很好。我想我需要映射所有这些网络控件。谢谢
    猜你喜欢
    • 2020-01-24
    • 2012-01-04
    • 2014-10-15
    • 2023-04-11
    • 2011-12-14
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 2014-01-10
    相关资源
    最近更新 更多