Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing DataTable from controller to PartialView

Tags:

asp.net-mvc

I'm looking for a way to pass a DataTable to the PartialView using a Controller Action. Or if you know better way, I'm open to suggestions.

Controller:

public DataTable GetDailyOutput()
{
    Graph g = repository.Graphs.Where(p => p.GraphID == 2).FirstOrDefault();
    DataTable dt = repository.GetGraphData(g.StoredProc);
    return dt;
}

View:

<div id="dvCategoryResults">
    @{Html.Partial("_GetDailyOutput", Html.Action("GetDailyOutput", "Graph"));}
</div>

Partial View:

@model System.Data.DataTable
@using System.Data
<table>
    <thead>
        <tr>
            @foreach (DataColumn col in Model.Columns)
            {
                <th>
                    @col.ColumnName
                </th>
            }
        </tr>
    </thead>
    <tbody>
       @foreach (DataRow row in Model.Rows)
       {
           <tr>
               @foreach (DataColumn col in Model.Columns)
               {
                    <td>
                        @row[col.ColumnName]
                    </td>
               }
            </tr>
        }
    </tbody>
</table>

My next step would be to update the table with an Ajax call and refresh the PartialView.

like image 629
Whistler Avatar asked Feb 01 '26 16:02

Whistler


1 Answers

You will probably need to use AJAX for this. You can put the code below in an event handler, such as the handler for a button click.

AJAX example using JQuery $.post():

$.post('@Url.Content("~/Graph/_GetDailyOutput")', function( data ) {
    $( "#dvCategoryResults" ).html( data );
});

Controller action:

public PartialViewResult _GetDailyOutput()
{
    Graph g = repository.Graphs.Where(p => p.GraphID == 2).FirstOrDefault();
    DataTable dt = repository.GetGraphData(g.StoredProc);
    return PartialView(dt);
}

If you prefer, you can render the partial view initially without using JavaScript by doing

<div id="dvCategoryResults">
        @Html.Action("_GetDailyOutput", "Graph")
</div>
like image 178
Inspector Squirrel Avatar answered Feb 04 '26 06:02

Inspector Squirrel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!