Reputation: 887
I am developing an ASP.Net MVC application. I want to get data from database using ajax. It does not load data in web page and also there is no error on the console window and is no exception in visual studio. Following is my Controller code.
[HttpGet]
public JsonResult GetCompanies()
{
try
{
IEnumerable<Company> company = _companyService.GetCompanies().ToList();
IEnumerable<CompanyListViewModel> viewModelListCompanies = Mapper.DynamicMap<IEnumerable<Company>, IEnumerable<CompanyListViewModel>>(company);
return new JsonSuccessResult(viewModelListCompanies);
//return Json(accountTypes, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)ResponseCode.UnprocessableEntity;
return new JsonErrorResult(ex.ToString());
}
}
This is the code in my view.
<div class="row">
<div class="col-md-9">
<div class="block">
<div class="header">
<h2>Sortable table</h2>
</div>
<div class="content">
<table cellpadding="0" cellspacing="0" width="100%" class="table table-bordered table-striped sortable" id="myDbTable">
<thead>
<tr>
<th data-hide width="20%">ID</th>
<th data-hide width="20%">Name</th>
<th data-hide width="20%">E-mail</th>
<th data-hide width="20%">Phone</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
}
@section Scripts{
<script>
var DataColumnsCount = 4;
//***Start Fatching Data for datatable *** start //
$.ajax({
type: 'POST',
url: @Url.Action("GetCompanies","Company"),
dataType: 'json',
data: "{}",
success: fetchCompanyTableList});
function fetchCompanyTableList() {
$('#myDbTable').DataTable({
ajax: {
url: @Url.Action("GetCompanies", "Company"),
type: "GET",
dataType: "json",
dataSrc: 'DataSet',
},
"columns": [
{"data" : "Id"},
{ "data": "Name" },
{ "data": "Email" },
{ "data": "Owner" }
],
"aoColumnDefs": [
{
"aTargets": [DataColumnsCount],
"mData": null,
"bSortable": false,
"mRender": function (data, type, fullRow) {
return '<th width="20%"><a href="#">Details</a></th>';
}
}
]
}
);
}
I am unable to figure out what really i am doing wrong. Please someone help in this regard.
Upvotes: 2
Views: 250
Reputation: 5284
You use [HttpGet]
in your action , means only allow http GET
request in your action.
But your ajax
call you use POST
request . That's not accept in your action. so change POST
to GET
if you need GET
request OR change [HttpGet]
to [HttpPost]
for POST
request .
You do't need multiple ajax
call.so need to change your ajax call because jquery datatable has own ajax call for data loading. you can fiend your answer this or this link. Or you can follow this YouTube video.
Upvotes: 1
Reputation: 1021
For Datatable You need Change TYPE to [HttpPost] & in you ajax change type "POST" As a developer you need add breakpoint to your controller & check its getting hit or not . Also you can console.log() / see result in browser developer tool
Upvotes: 2