JQuery Datatable not loading Json data from MVC Controller - json

I have an Asp.Net MVC 5 web application. I am using JQuery Datatables v1.10.16 to display tabular data within one of the razor views. The data being returned to the datatable is via an ajax call and returning Json.
This is my razor view
<table id="data_table" class="display" style="width:100%">
<thead>
<tr>
<td>Evaluation ID</td>
<td>Applicant Name</td>
</tr>
</thead>
<tfoot>
<tr>
<td>Evaluation ID</td>
<td>Applicant Name</td>
</tr>
</tfoot>
</table>
<script type="text/javascript">
$(document).ready(function () {
$('#data_table').DataTable({
"ajax": '/EvalDashboard/GetEvaluationData',
"dataSrc": 'evaluations',
"columns": [
{ data: 'evaluationID' },
{ data: 'applicantName' }
]
});
});
</script>
This is my method which is called inside the controller EvalDashboard
public JsonResult GetEvaluationData()
{
var evaluations = _evalService.GetAllCecEvaluations(null, null)
.Take(20).Select(x => new
{
evaluationID = x.EvaluationID,
applicantName = x.tblcourseapplicant.FullName
}).ToList();
return Json(evaluations, JsonRequestBehavior.AllowGet);
}
When I run the app, I can see that the method GetEvaluationData() is being called, however, no data is returned to the datatable in the view, I only get a message saying Loading...
I'm not sure if the problem is because I'm returning an annonymous type inside my method.
Could someone please help?
Thanks.

The problem was that I had not included the keyword data inside the Json return statement like so:
return Json(new { data = evaluations }, JsonRequestBehavior.AllowGet);
This fixed the problem I was having.

Related

Load JSON in gist into table using query

I'm attempting to load a series of json results on GitHub into a table. The gist can be found here. I've had a look at this question which helps with the population of the table. However, I'm having trouble retrieving the data from the gist.
I've modified the data section of the question as below
<script type="text/javascript">
var $table = $('#table');
$.getJSON('https://gist.githubusercontent.com/TheMightyLlama/9f4f1b4c2c078a6080c9212aba6beb59/raw/092fc02afcbd11ea26e7a08541b8dfae4748218a/News%2520Summary%2520Sample', function(mydata) {
});
$(function () {
$('#table').bootstrapTable({
data: mydata
});
});
</script>
And the table as below:
<div class="container">
<table id="table" data-height="460">
<thead>
<tr>
<th data-field="title">Title</th>
<th data-field="date">Date</th>
<th data-field="category">Category</th>
</tr>
</thead>
</table>
</div>
The variable mydata you used in getJSON function is local variable and that was just created at the time when that function called and can only usable within that function. Write the load table code inside getJSON
Here is JSFiddle Working Link
var $table = $('#table');
$.getJSON('https://gist.githubusercontent.com/TheMightyLlama/9f4f1b4c2c078a6080c9212aba6beb59/raw/092fc02afcbd11ea26e7a08541b8dfae4748218a/News%2520Summary%2520Sample', function(mydata) {
$('#table').bootstrapTable({
data: mydata
});
});

Bind first value and remove all other repeating value from a ng-repeat

I have a scenario to bind a html table using angular js. In my table i need to show an a tag based on another column value(Payment Status). If its fully paid no need to show the a tag, else need to show it for very next element. I am a new one in angular.
<table>
<thead>
<tr>
<th>Month</th>
<th>Installement</th>
<th>PaymentAmount</th>
<th>PaymentDate</th>
<th>Payment Status</th>
<th>Pay</th>
</tr>
</thead>
<tbody>
<tr dir-paginate="row in rowCollection|orderBy:type:reverse|filter:searchKeyword|itemsPerPage:maxsize">
<td>{{row.Month}}</td>
<td>{{row.MonthlyInstallement}}</td>
<td>{{row.PaymentAmount}}</td>
<td>{{row.PaymentDate}}</td>
<td>{{row.PaymentStatus}}</td>
<td ng-if="row.PaymentStatus == 'UNPAID'">
Pay Online
</td>
<td ng-if="row.PaymentStatus == 'FULLY_PAID'">
</td>
</tr>
</tbody>
</table>
function bindFinanceDetails() {
var finUrl = baseurl + 'api/FinancialStatement/GetCarFinanceInfo';
var req = {
method: 'post',
data: {
LoginID: LoginID,
ContractNumber: 11170200669,
CustomerId: 2355898046
},
url: finUrl,
headers: {
RequestedPlatform: "Web",
RequestedLanguage: cookiePreferredLanguage,
Logintoken: $cookieStore.get('LoginToken'),
LoginId: LoginID
}
};
$http(req).then(function(response) {
var getData = response.data.FinanceList;
$scope.rowCollection = getData;
}, function(error) {
toastr.error($filter('translate')('Error Occured'));
});
}
A quite hacky solution will be something like the following (just showing you the needed change in the unpaid td element):
<td ng-if="row.PaymentStatus === 'UNPAID'" ng-show="$index === data.payOnlineIndex"
ng-init="data.payOnlineIndex = (!data.payOnlineIndex || (data.payOnlineIndex > $index)) ? $index : data.payOnlineIndex">
Pay Online
</td>
This way ng-init will run for all unpaid elements, setting the smallest index to the payOnlineIndex variable. ng-show will make sure to only show that one element that has the smallest index.
I encapsulate payOnlineIndex with a data object to keep a stable reference to it. This also requires the following addition to the controller code:
$scope.data = { payOnlineIndex: null };
See a working jsFiddle example here: https://jsfiddle.net/t3vktv0r/
Another option is running your filter and orderBy in the controller, searching for the first occurrence of an "unpaid" row, and marking that element for the "pay online" feature with some flag you can test with ng-if in your view.

ng repeat after postDigest not working

I am trying to load data from list to repeater but its not working the data is returning, list of students but its not showing on screen.
Controller:
$scope.students=[];
$scope.$$postDigest(function () {
$http.get("/getAllStudents"/*, {timeout: canceler.promise}*/).
then(function (response, status, headers, config) {
if (response.data) {
$scope.students=response.data;
}
});
});
HTML:
<tr ng-repeat="student in students">
<td contenteditable="true">{{student.Id}}</td>
<td contenteditable="true">{{student.FullName}}</td>
<td contenteditable="true">{{student.Gender}}</td>
<td contenteditable="true">{{student.Grade}}</td>
</tr>
When the $http.get the call is made in the postDigest, it seems the data is successfully inserted inside the $scope.students. Please check if there is any scope issue, because as per the details provided, it should work until and unless you're missing to mention any other details.

send data from two models of Mongoose inside Express.js to display in view list data

I have a Shopping Website I want to be able to display two model names "jeans" and "shirt" in a view
I need to pass data from two models I know how to access data from two models in one controller but I do not know how to send data from that controller
Controller:
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Shirt = mongoose.model('Shirt'),
Jeans = mongoose.model('Jeans');
exports.list = function(req, res) {
Jeans.find().sort('-created').populate('user', 'displayName').exec(function(err, jeans) {
Ajean = jeans;
});
Shirt.find().sort('-created').populate('user', 'displayName').exec(function(err, shirts) {
Ashirt = shirts;
});
Shirt.find().sort('-created').populate('user', 'displayName').exec(function(all) {
// res.jsonp(Ashirt);
// res.jsonp(Ajean);
});
};
View:
<div class="list-group">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Color</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="item in items">
<td data-ng-bind="item.name"></td>
<td data-ng-bind="item.color"></td>
</tr>
</tbody>
</table>
</div>
I know that I cannot use "res.jsonp();" more than once .
when I use "Ajean" it give me data for "jeans" and
when I use "Ashirt" it give me data from "shirts" model
But I want to be able to show both data from both "shirt" model and "jean" model
How Can I do That?
Do I need to merge two Json?
How should I change my view to see that data?
Thanks!
You could try nesting the queries and then merge the resulting arrays with Array.concat:
Jeans.find().sort('-created').populate('user', 'displayName').exec(function(err, jeans) {
Shirt.find().sort('-created').populate('user', 'displayName').exec(function(err, shirts) {
var all = shirts.concat(jeans);
res.jsonp(all);
});
});

Retrieving values from a table cell <td> to a controller

I'm trying to get a specific value from a table cell and pass is to a controller. But it doesn't seem to be working. I show you some of my codes:
This is in the controller:
def searchUser = {
String abc = request.getParameter("harrow")
println(abc)
}
This is in the html page:
<form>
<div style="height: 250px; overflow: scroll; width: 100%;">
<table id="normal">
<g:each in = "${result}">
<tr id="btn">
<td width=10% >${it.ID}</td>
<td width=25% id="harrow">${it.username}</td>
</tr>
</g:each>
</table>
</div>
<input type ="submit" name ="abc" id="opener">
</form>
EDIT
AJAX:
$("#edittable").on('click', function() {
$.ajax({
url: URL,
data: $(this).serialize(),
type: "POST",
success: function(html){
//do something with the `html` returned from the server here
$("#edit1").html(html).dialog("open")
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;//suppress natural form selection
});
I can get the value to pass to the controller, but right now it only retrieves the first row of values rather than the other. Is there something wrong with my AJAX codes? Thank you guys so much.
So to show details of the row, one of the approaches can be:
CONTROLLER METHODS
def rows = [
[id:1, name:'name1'],
[id:2, name:'name2'],
[id:3, name:'name3']
]
def show(){
[results:rows]
}
def showLine(Long id){
render rows.find {it.id == id }
}
VIEW
<html>
<head>
<g:javascript library="jquery" />
<r:layoutResources />
</head>
<body>
<table>
<thead>
<tr>
<th>Action</th>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<g:each in="${results}" status="i" var="r">
<tr>
<td><g:remoteLink value="Details" id="${r.id}" action="showLine" update="lineDetails">Details</g:remoteLink></td>
<td>${r.id}</td>
<td>${r.name}</td>
</tr>
</g:each>
</tbody>
</table>
<div id="lineDetails">
</div>
</body>
</html>
Basically you call showLine method using AJAX and passing row object id. Then you search for the object and render it back. Rendered data is put into div under the table. It's up to you if you use onclick, button or link in the table. It's also up to you how to show details on results page - use jquery dialog, or something else. Hope it helps