Reputation: 1145
I am building one Report page for all reports based on @RouteData.Values
. My all reports comes from HomeController
and I just want to display them to a #table1
in Razor Page.
Reports are dynamic size in row and column.
Reports RazorPageView
@page "{id}"
@model Test.Pages.Reports.IndexModel
<table id="table1" class="table table-responsive">
</table>
@section Scripts {
<script type="text/javascript">
$(document).ready(function () {
var id = @RouteData.Values["id"];
switch (id) {
case 'Customers':
apipath = 'GetAllCustomers';
break;
case 'Vendors':
apipath = 'GetAllVendors';
break;
default:
apipath = 'SomeOtherReport';
}
$.ajax({
url: "/Home/" + apipath,
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: JSON,
success: function (result) {
//Here I want to load dynamic type table data to #table1
}
});
});
</script>
}
HomeController
:
public class HomeController : Controller
{
[HttpGet]
public ActionResult GetAllCustomers()
{
var result = _Context.Customers.ToList();
return Json(result);
}
[HttpGet]
public ActionResult GetAllVendors()
{
var result = _Context.Vendors.ToList();
return Json(result);
}
}
So that my url looks "~/Reports/Customers" or "~/Reports/Vendors"
Upvotes: 1
Views: 1988
Reputation: 1867
Add below to your success callback.
var allProperties = Object.getOwnPropertyNames(result[0]);
var tableHeader ='<tr>';
for(var i=0; i<allProperties.length; i++)
{
tableHeader += '<th>'+allProperties[i]+'</th>'
}
var allRows = tableHeader + '</tr>';
for(var index =0;index<result.length; index++)
{
var row = '<tr>';
for(var i=0; i<allProperties.length; i++)
{
row += '<td>'+result[index][allProperties[i]]+'</td>'
}
row += '</tr>';
allRows += row;
}
$('#table1').append(allRows);
Upvotes: 1
Reputation: 598
Try Following
if following is your ajax
success
function
and suppose in the result
ur getting columns (id,name,address)
success: function (result) {
var reportBody='';
$('#table1').empty();//clear table body
if(result.d.length>0)
{
//create body using $.each
$.each(result.d,function(i,info){
reportBody+='<tr><td>'+info.id+'</td><td>'+info.name+'</td><td>'+info.address+'</td></tr>'
});
}
else
{
reportBody+='<tr><td>There is no Record</td></tr>'
}
//append body to table table1 as follow
$('#table1').append('<thead><tr><th>ID</th><th>Name</th><th>Address</th></tr></theah><tbody>'+reportBody+'</tbody>');
}
Upvotes: 2