How to load HTML Table in MVC using ViewData?
Asked Answered
I

1

6

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...

Interfuse answered 12/11, 2013 at 22:35 Comment(5)
How about @ViewData["MattersTable"] (no brackets and no semicolon)?Lafrance
I got the Whole plain string before table and then empty table with only headers...Interfuse
Yeah, you'll also want to wrap it with Html.Raw() since you're passing a raw html string ... @Html.Raw(ViewData["MattersTable"])Lafrance
how about making this a partial view and not concatin string server side ?Carbonous
Just as a side-comment, and agreeing with adt, please don't do this for production code ;)Noose
L
8

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>
Lafrance answered 12/11, 2013 at 22:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.