How to create dynamic HTML table in ASP.Net MVC (analog HtmlTable in webforms)

淺唱寂寞╮ 提交于 2019-12-23 02:57:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!