问题
How to create dynamic table with the complex structure and different styles of cells?
I have a lot of code such as:
In Controller:
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>";
}
In View:
<table>
<tr>
@Html.Raw(ViewBag.htmlRawName1 )
</tr>
<tr>
@Html.Raw(ViewBag.htmlRawName2 )
</tr>
</table>
Can I use HtmlHelper instead of this?
回答1:
You should pass your data to the view in your controller action :
in your controller :
List<YourClass> viewModel = list;
ViewBag.NbColumns = 5; //Number of your table's columns
return View(list);
in your view :
@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>
来源:https://stackoverflow.com/questions/16713682/how-to-create-dynamic-html-table-in-asp-net-mvc-analog-htmltable-in-webforms