在 Asp.Net 中在服务器端创建标签

Create label on ServerSide in Asp.Net

我需要从代码中创建标签。

代码示例:

var lbl = new Label { Text = "Test", CssClass = "control-label text-right" };

作为 html 的结果,我得到 <span>... 而不是 <label>...

如何创建 <label>...

我应该像 HtmlGenericControl 那样创建它吗?

您只需将 <asp:Label /> 上的 AssociatedControlID 设置为相关文本即可。这样做的原因是您通常使用标签作为文本框的标题,因为这是 HTML 标签的性质。

When the AciatedControlID property is set, the Label control renders as an HTML label element, with the for attribute set to the ID property of the associated control. You can set other attributes of the label element using the Label properties. For example, you can use the Text and AccessKey properties to provide the caption and hot key for an associated control.

这是 MSDN 中关于 属性 !

Article