C# asp.net 从代码隐藏页面插入 HTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16885081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:02:38  来源:igfitidea点击:

asp.net insert HTML from Code Behind page

c#asp.netcss

提问by Gianmarco Spinaci

I've got a problem with ASP.NET. I'm using C#.

我遇到了 ASP.NET 的问题。我正在使用 C#。

With a SQL query i have the number exactly of rows in a Database, i need to write the same number of div tag to show the results.

使用 SQL 查询,我在数据库中拥有准确的行数,我需要编写相同数量的 div 标记来显示结果。

This is the code

这是代码

count is a variable that contain the number of rows.

count 是一个包含行数的变量。

Projects is a List

项目是一个列表

for (int i = 0; i < count; i++)
{
    form1.Controls.Add(new Literal() { 
         ID = "ltr" + i,

         Text = "<div class= 'container' >Name = " + Projects[i].Name + " ;</div>" });
}

But there is a problem, i must place these div into another div with ID = Container.

但是有一个问题,我必须将这些 div 放入另一个 ID = Container 的 div 中。

in this way Literal controls aren't placed into div#Container

通过这种方式,文字控件不会放入 div#Container

How can i do to place the For results into a div?

如何将 For 结果放入 div?

采纳答案by Andrei

Instead of Literalcontrol, which is designed to render text, not html tags, you can use either HtmlGenericControl:

Literal您可以使用以下任一方法,而不是旨在呈现文本而非 html 标签的控件HtmlGenericControl

HtmlGenericControl div = new HtmlGenericControl();
div.ID = "div" + i;
div.TagName = "div";
div.Attributes["class"] = "container";
div.InnerText = string.Format("Name = {0} ;", Projects[i].Name);
form1.Controls.Add(div);

or Panelcontrol, which is rendered into div, with Literalinside it:

Panel控件,呈现为 div,其中Literal包含:

Panel div = new Panel();
div.ID = "panel" + i;
div.CssClass = "container";    
div.Controls.Add(new Literal{Text = string.Format("Name = {0} ;", Projects[i].Name)});    
form1.Controls.Add(div);

回答by Mohd. Umar

Instead U Should Use Repeater Control, it'll be quite easy to work with.

相反,你应该使用中继器控制,它会很容易使用。

Steps

脚步

  1. Take a SqlDatasource.
  2. Take a repeater Control.
  3. Set its datasource to .
  4. Design the itemTemplate as you like.
  5. Done..!
  1. 取一个 SqlDatasource。
  2. 拿一个中继器控制。
  3. 将其数据源设置为 .
  4. 根据需要设计 itemTemplate。
  5. 完毕..!

If have any doubt follow this LINK

如果有任何疑问,请关注此链接