Html 如何在 ASP.NET 中为无序列表动态生成列表项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1809125/
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-29 01:24:37  来源:igfitidea点击:

How can you dynamically generate list items to an unordered list in ASP.NET?

asp.nethtmlvb.net.net-2.0

提问by Mark

I have an error panel that is subbed in to a page if an error goes wrong to gracefully handle and display errors. Currently, I am just appending the error messages to a string and pushing that to a label. If you have multiple errors, this gets messy. Therefore, I'd like to push each error to a list item in a bulleted, unordered list.

我有一个错误面板,如果错误出现错误以正常处理和显示错误,它会嵌入到页面中。目前,我只是将错误消息附加到字符串并将其推送到标签。如果您有多个错误,这会变得混乱。因此,我想将每个错误推送到项目符号无序列表中的列表项。

How can I dynamically generate, from a vb codebehind file, new list items inside of an undordered list element?

如何从 vb 代码隐藏文件动态生成无序列表元素内的新列表项?

回答by Phaedrus

Why not use a BulletedListcontrol? This control will render an unordered list to the client.

为什么不使用BulletedList控件?此控件将向客户端呈现一个无序列表。

<asp:BulletedList ID="BulletedList" runat="Server" BulletStyle="NotSet">
</asp:BulletedList>

You can then add list items programmatically from code behind like this.

然后,您可以像这样从后面的代码中以编程方式添加列表项。

BulletedList.Items.Add("Item1");

You can also accomplish this by adding runat='server'to reference the ULtag server side.

您还可以通过添加runat='server'以引用UL标记服务器端来完成此操作。

<ul id="uList" runat="server">
</ul>

Then in the code behind use the InnerHtmlproperty to programmatically add LItags to the contents within the opening and closing ULtags.

然后在后面的代码中使用该InnerHtml属性以编程方式LI向开始和结束UL标记内的内容添加标签。

uList.InnerHtml += "<li>Item1</li>";

回答by cdeweese

You could use a page level variable to hold the errors, like a list or an array. Then just write a method that does something like:

您可以使用页面级变量来保存错误,例如列表或数组。然后只需编写一个执行以下操作的方法:

Private Sub WriteErrors()
  lblErrors.txt = "<ul>"
  For Each s as String in _myErrors
   me.lblErrors.Text &= "<li>" & s & "</li>"
  End For
  lblErrors.Text &= "</ul>" 
End Sub