1

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 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.