0

So i tried to make tables on controller here's the code i was typing

 DataTable table = new DataTable();
        Table.Columns.Add("Nama", typeof(string));
        Table.Columns.Add("Nama2", typeof(string));

        Table.Rows.Add("Manama", "Jeff");
        Table.Rows.Add("Damn", "Daniel");

        ViewData["Test"] = Table;



@ViewData["Test"] // when i type this it doesnt show anything on new page when i run it
Arra
  • 35
  • 6
  • Note that your `ViewData` contains `DataTable`, and using `@ViewData["Test"]` will return fully-qualified name e.g. `System.Data.DataTable` instead of its content (because `ToString()` is implicitly called). You need to iterate the `DataTable` as `IEnumerable` to get its results. – Tetsuya Yamamoto Dec 11 '18 at 01:48

1 Answers1

1

The problem you have is @ViewData["Test"] implicitly calls ToString() to the DataTable object, which will return fully-qualified name of System.Data.DataTable instead of its contents (rows & columns). If you want to create a table from it, you should create HTML <table> structure like this:

@using System.Data
@{
    var table = ViewData["Test"] as DataTable;
}

<table>
   <thead>
       <tr>
           @foreach (DataColumn col in table.Columns)
           {
               <th>@col.Caption</th>
           }
       </tr>
   </thead>
   <tbody>
        @foreach (DataRow row in table.Rows)
        {
            <tr>
                @foreach (var cell in row.ItemArray)
                {
                    <td>@cell.ToString()</td>
                }
            </tr>
        }
    </tbody>
</table>

Or better passing DataTable directly to model:

Controller Action

DataTable table = new DataTable();
table.Columns.Add("Nama", typeof(string));
table.Columns.Add("Nama2", typeof(string));

table.Rows.Add("Manama", "Jeff");
table.Rows.Add("Damn", "Daniel");

return View(table);

View

@using System.Data

<table>
   <thead>
       <tr>
           @foreach (DataColumn col in Model.Columns)
           {
               <th>@col.Caption</th>
           }
       </tr>
   </thead>
   <tbody>
        @foreach (DataRow row in Model.Rows)
        {
            <tr>
                @foreach (var cell in row.ItemArray)
                {
                    <td>@cell.ToString()</td>
                }
            </tr>
        }
    </tbody>
</table>

This fiddle contains live example how you should create the table inside view page.

Related issue:

Displaying standard DataTables in MVC

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61