Arra
Arra

Reputation: 35

ViewData doesn't show any data when called

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

Upvotes: 0

Views: 227

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

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

Upvotes: 1

Related Questions