如何在ASP.Net MVC中创建动态HTML表格(webforms中的模拟HtmlTable)

问题描述:

如何创建具有复杂结构和不同样式单元格的动态表?


我有很多代码,例如:

How to create dynamic table with the complex structure and different styles of cells?
I have a lot of code such as:

在控制器中:

string styleTag = "class=\"someCssStyle\"";
ViewBag.htmlRawName1 += "<td colspan=\"" + colspan +
                    "\" " + styleTag + ">" + name + "</td>";
                for (int i = 0; i < list.count; i++)
                {
                    ViewBag.htmlRawName2 += "<td " + styleTag + ">" + list[i].Name +
                        "</td>";
                }

在视图中:

<table>
   <tr>
       @Html.Raw(ViewBag.htmlRawName1 )
   </tr>
   <tr>
       @Html.Raw(ViewBag.htmlRawName2 )
   </tr>
</table>

我可以使用HtmlHelper代替吗?

Can I use HtmlHelper instead of this?

您应该将数据传递给控制器​​操作中的视图:

You should pass your data to the view in your controller action :

在控制器中:

List<YourClass> viewModel = list;
ViewBag.NbColumns = 5; //Number of your table's columns
return View(list);

在您的视图中:

@model List<YourClass>

<table>
  <tr>
    <td colspan="@ViewBag.NbColumns">Name</td>
  </tr>
  <tr>
    @foreach(var item in Model) {
        <td class="someCssStyle">@item.Name</td>
    }
  </tr>
<table>