【问题标题】:Creating a table programmatically以编程方式创建表
【发布时间】:2015-12-05 13:35:36
【问题描述】:

我一直在寻找相当长的时间来使用 C# 通过代码隐藏创建下表。我很难将<tr> 添加到<thead><tr><tbody>。表格应该是这样的:

<table id="mytable" border="1" cellpadding="10" cellspacing="0" >
     <caption>myCaption</caption>
     <thead>
         <tr>
             <td>&nbsp;</td>
             <th scope="col">myHeader1</th>
             <th scope="col">myHeader2</th>
             <th scope="col">myHeader3</th>
         </tr>
     </thead>
     <tbody>
         <tr>
             <td>2</td>
             <td>3</td>
             <td>1</td>
         </tr>
     </tbody>
 </table>

感谢任何帮助。

【问题讨论】:

标签: c# asp.net asp.net-mvc html-table


【解决方案1】:

我使用 C# MVC 做过类似的事情。这是一个示例代码。希望这将有助于获得一个想法。

@{int count = Model.HeadingsList.Count;}
<table>
    <thead>
        <tr>
            @foreach (string heading in Model.HeadingsList)
            {
                <th>@heading</th>
            }
        </tr>
    </thead>
    <tbody>
        @foreach (string row in Model.rowsList)
        {
            string[] cellValues = Array.ConvertAll(row.Split(','), p => p.Trim());
            if (count != cellValues.Count()) { return; } 
            <tr>
                @for (int i = 0; i < @count; i++) 
                {
                            <td>@cellValues[i]</td>
                }
            </tr>
        }
    </tbody>
</table>

我有一个如下所示的行列表。 数组[0]['cell1','cell2','cell3'...] 数组[1]['cell1','cell2','cell3'...]

【讨论】:

    【解决方案2】:

    使用您要绑定的任何内容的列表创建一个强类型视图,并使用@foreach 循环:

    @model List<MyClass>
    
    <table id="mytable" border="1" cellpadding="10" cellspacing="0" >
     <caption>myCaption</caption>
     <thead>
         <tr>
             <td>&nbsp;</td>
             <th scope="col">myHeader1</th>
             <th scope="col">myHeader2</th>
             <th scope="col">myHeader3</th>
         </tr>
     </thead>
     <tbody>
        @foreach(var m in Model)
        {
         <tr>
             <td>@m.MyProp1</td>
             <td>@m.MyProp2</td>
             <td>@m.MyProp3</td>
         </tr>
        }
     </tbody>
    

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 1970-01-01
      • 2012-04-19
      • 1970-01-01
      • 2016-11-03
      • 2013-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多