【问题标题】:How to show a List <string> within an Object in the GridView BoundFeild DataField asp.net webforms.如何在 GridView BoundFeild DataField asp.net webforms 的对象中显示列表 <string>。
【发布时间】:2026-01-04 02:30:01
【问题描述】:

我在数据库中有一个 JSON 字符串存储在这样的一列中:

Image JSON Text stored within Database

然后我从数据库中检索这段字符串并将其反序列化为我的 aspx.cs 文件中的配置对象。

从那里我通过迭代反序列化的 Config 对象并将其添加到列表中来创建组件对象列表。 (因为配置对象会存储多个组件对象)。

然后我想使用 GridView 控件在浏览器中显示我的组件对象列表。除了组件对象的属性之一是字符串列表之外,我能够显示所有属性。

我希望能够在一个单元格中显示整个列表(对于每个对象)。但是它向我展示了这样的:

Image of GridView

正如您在上面角色列下的 GridView 图像中看到的那样,它没有向我显示角色列表中的值。

我怎样才能让它显示出来?

我用于创建组件列表并将其绑定到数据源的代码是:

List<Component> componentListForGridView = new List<Component>();
        foreach(Component comp in DeserializedObject.Component)
        {
            componentListForGridView.Add(comp);
        }

        GridView1.DataSource = componentListForGridView;
        GridView1.DataBind();

我在 aspx 中显示表格的代码是:

    <asp:GridView ID="GridView1" AutoGenerateColumns="false"  runat="server">
        <columns>
            <asp:BoundField DataField="id" HeaderText="ID" />
            <asp:BoundField DataField="visible" HeaderText="Visible" />
             <asp:BoundField DataField="roles" HeaderText="Role" />
            <asp:BoundField DataField="childControls.controlList[0].id" HeaderText="ControlId" />
            <asp:BoundField DataField="childControls.controlList[0].src" HeaderText="ControlSrc"/>
        </columns>
    </asp:GridView>

我的 Component 类的结构是:

 public class Component
{
    public string id { get; set; }
    public string visible { get; set; }


    public List<string> roles { get; set; }
    public ChildControls childControls { get; set; }

}

角色列表是通过从表单上的文本框中拆分逗号分隔的字符串值来创建的。

JSON 文本粘贴在下面以供参考:

{ "Component": [
{
  "id": "companyEmployee",
  "visible": "true",
  "roles": [
    "manager",
    "employee"
  ],
  "childControls": {
    "controlList": [
      {
        "id": "compLogo",
        "src": "content/images/epharma_logo__u40.png#"
      }
    ]
  }
},
{
  "id": "noman",
  "visible": "false",
  "roles": [
    "manager",
    "employee",
    "employer"
  ],
  "childControls": {
    "controlList": [
      {
        "id": "test",
        "src": "content/images/epharma_logo__u40.png#"
      }
    ]
  }
} ]}

【问题讨论】:

    标签: c# asp.net list gridview webforms


    【解决方案1】:

    你可以试试:

    在代码中创建一个用于渲染角色列表的方法

    protected string DisplayRoles(Component component) {
       string displayOutput = String.Empty;
    
       if(component!=null) {
          foreach(string role in component.roles) {
            displayOutput+=role + "<br/>";
        }
      }
    
        return displayOutput;
    }
    

    使用 GridView ItemTemplate 字段而不是 Bounded Field 并调用在步骤 1 中创建的方法:

    <asp:TemplateField HeaderText="Role">
                <ItemTemplate>
                    <%# DisplayRoles((Component)Container.DataItem) %>
                </ItemTemplate>
    
            </asp:TemplateField>
    

    【讨论】:

    • 谢谢,它现在可以完成这项工作。