【问题标题】:Custom render CheckBoxList items to have a class set on the LI自定义渲染 CheckBoxList 项目以在 LI 上设置一个类
【发布时间】:2012-12-20 16:39:35
【问题描述】:

我有一个 CheckBoxList(框架版本 4),RepeatLayout 设置为 UnOrderedList。我想在每个 LI 上生成一个类来简化一些客户端编码和样式,但是我做不到。

我重写RenderItem方法如下:

protected override void RenderItem(ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer)
{
    ListItem item = Items[repeatIndex];
    String id = ClientID + "_" + repeatIndex.ToString();
    String name = UniqueID + "$" + repeatIndex.ToString();

    writer.Write(@"<li class='{0}'>", "tcsdrp_day" + (item.Selected ? " selected" : ""));
    writer.Write(@"<input id='{0}' type='checkbox' name='{1}' value='{2}'>", new object[] { id, name, item.Value });
    writer.Write(@"<label for='{0}'>{1}</label>", new object[] { id, item.Text });
    writer.Write(@"</li>");
}

但是,我得到了大量生成的空白 LI,因此很明显它们是在调用者或其他地方呈现的,我终生无法确定在哪里。

现在通过将类添加到 ListItems 中解决了这个问题,但这会创建一个额外的 SPAN,我希望丢失它。

有什么好的方法吗?

编辑:这是一个精简的演示;最终版本将具有基于原始数据项属性生成不同类的逻辑,以防有人想知道我为什么需要添加一个类。

编辑 2:我现在解决了通过将 RenderItem 更改为使用 label-wrapping-the-input 样式来简化标记的直接问题:

writer.Write(@"<label class='{0}'>", labelclass);
writer.Write(@"<input id='{0}' type='checkbox' name='{1}' value='{2}'{3}>", new object[] { id, name, item.Value, item.Selected ? " checked" : "" });
writer.Write(item.Text);
writer.Write(@"</label>");

我仍然想知道是否有任何方法可以完全自定义项目渲染。

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    在 PreRender 事件中,遍历 Items-Collection,并根据需要分配类:

    For Each l As ListItem In Items
      If l.Value = "1" Then
        l.Attributes.Add("class", "myClass")
      End If
    Next l
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-03
      • 2015-02-13
      • 2017-03-06
      相关资源
      最近更新 更多