How to load HTML Table in MVC using ViewData?

Bryuk picture Bryuk · Nov 12, 2013 · Viewed 7.7k times · Source

I have the following table in my View:

<table id="tblHelpRow">
    <thead>
        <tr class="title">
            <th>
                1
            </th>
            <th>
                2
            </th>
            <th>
                3
            </th>
            <th>
                4
            </th>
        </tr>
    </thead>
    <tbody id="helpRowBody">       
        @{ ViewData["MattersTable"].ToString(); }
    </tbody>
</table>

In my controller I create a body for this table and add to the DataView. I'm getting to this controller by redirect from another and passing my DataTable. In real I have a little bit different, but here I wrote as simple as possible to show the Problem:

public ActionResult Matters(DataTable source)
{
       string result = "";
       foreach(DataRow dr in source.Rows)
       {
            result += "<tr>" +
            "<td>" + dr["1"] + "</td>" +
            "<td>" + dr["2"] + "</td>" +
            "<td>" + dr["3"] + "</td>" +
            "<td>" + dr["4"] + "</td>" +
            "</tr>";
       }
       ViewData["MattersTable"] = result;
       return View();
}

But as a result I got page with Column Headers but no content inside... Source page tells me that nothing is inside of tbody...

Answer

Peter picture Peter · Nov 12, 2013

Try this:

<table id="tblHelpRow">
    <thead>
        <tr class="title">
            <th>
                1
            </th>
            <th>
                2
            </th>
            <th>
                3
            </th>
            <th>
                4
            </th>
        </tr>
    </thead>
    <tbody id="helpRowBody">       
        @Html.Raw(ViewData["MattersTable"])
    </tbody>
</table>