While implementing Data table in Spring Boot MVC Project with Thymeleaf ,no any data populate in data table - spring

My Service,Controller and Views are :
public class LoadDataService {
public List<Employee> getEmployeeList(){
List<Employee> employeeList = new ArrayList<Employee>();
Employee employee1 = new Employee("Sridharan","Junior Blogger","5000","India");
Employee employee2 = new Employee("Arul Raj","Senior Blogger","105000","China");
Employee employee3 = new Employee("Priya","Associate","21000","Australia");
Employee employee4 = new Employee("Sam","Associate","20030","Australia");
Employee employee5 = new Employee("Ram","Associate","2020","Australia")
employeeList.add(employee5);
employeeList.add(employee4);
employeeList.add(employee3);
employeeList.add(employee2);
employeeList.add(employee1);
return employeeList;
}
#Override
public String toString() {
return "LoadDataService [getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()="
+ super.toString() + "]";
}
}
Controller class :
#Controller
public class JQueryDatatableController {
private static final Logger logger = LoggerFactory.getLogger(JQueryDatatableController.class);
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home(Locale locale, Model model) throws JsonGenerationException, JsonMappingException, IOException {
logger.info("Welcome home! The client locale is {}.", locale);
LoadDataService dataService = new LoadDataService();
ObjectMapper mapper = new ObjectMapper();
ModelAndView mav=new ModelAndView();
mav.addObject("employeeList", mapper.writeValueAsString(dataService.getEmployeeList()));
mav.setViewName("index");
return mav;
}
}
data table integration in HTML thymeleaf page is :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Datables Demo</title>
<script type="text/javascript" th:src="#{js/jquery-1.12.1.min.js}" ></script>
<script th:src="#{js/jquery.dataTables.js}"></script>
<!--CSS StyleSheet -->
<link rel="stylesheet" type="text/css" th:href="#{/css/common.css}"/>
<link rel="stylesheet" type="text/css" th:href="#{/css/jquery.dataTables.css}">
</head>
<body>
<div>
<img class="dataTableExample" th:src="#{/images/JQueryDatatableandSpringMVC.png}">
</div>
<table id="example" class="display" cellspacing="0" width="100%" style="overflow-x:auto">
<thead>
<tr>
<th>Name</th>
<th>Designation</th>
<th>Salary</th>
<th>Country</th>
</tr>
</thead>
</table>
<script th:inline="javascript">
$(document).ready(function () {
$('#example').DataTable({
"searching": true,
"serverSide":false,
"paging":true,
"sAjaxSource":"${employeeList}",
"columns": [
{"data": "name"},
{"data": "designation"},
{"data": "salary"},
{"data": "country"}
]
})
});
</script>
</body>
</html>
Screenshot of Error

Try assigning Employee List to 'data' like below,
<script th:inline="javascript">
var empList = ${employeeList};
$(document).ready(function () {
$('#example').DataTable({
"searching": true,
"serverSide":false,
"paging":true,
"data": empList,
"columns": [
{"data": "name"},
{"data": "designation"},
{"data": "salary"},
{"data": "country"}
]
})
});
</script>
https://datatables.net/manual/data/

After multiple try and reading a lot of problem ,i find the answer
<script type="text/javascript" th:inline="javascript">
var empList = [# th:utext="${employeeList}"/];
$(document).ready(function () {
console.log(empList);
$('#example').DataTable({
"aaData":empList,
"aoColumns": [
{"mDataProp": "name"},
{"mDataProp": "designation"},
{"mDataProp": "salary"},
{"mDataProp": "country"}
]
})
});
</script>

Related

Ajax in MVC Page is not consuming a method in Controller

I am very new to MVC .net core. I am implementing an ajax call in my Page to a Datatable but somehow it is not invoking my method in a controller. I do not get any error in my console. My code is below:
startup => Configuration
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllersWithViews();
services.AddRazorPages().AddRazorRuntimeCompilation();
}
startup => Configure
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
});
_Layout.cshtml
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - AMS Customers</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" />
</head>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
#RenderSection("Scripts", required: false)
CustomerController
[Route("api/Customer")]
public class CustomerController : Controller
{
private readonly ApplicationDbContext context;
public CustomerController(ApplicationDbContext context)
{
this.context = context;
}
[HttpGet]
public async Task<IActionResult> GetAll()
{
return Json(new { data = await context.Customers.ToListAsync() });
}
}
index.cshtml => For customer List
<div class="col-12 border p-3">
<table id="dt_load" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Plate Number</th>
<th>Time Stamp</th>
<th></th>
</tr>
</thead>
</table>
</div>
#section Scripts {
<script src="~/js/customer.js"></script>
}
customer.js
var dataTable;
$(document).ready(function () {
loadDataTable();
});
function loadDataTable() {
dataTable = $('#dt_customers').DataTable({
"ajax": {
"url": "/api/customer",
"type": "GET",
"dataType": "json"
},
"columns": [
{ "data": "firstName"},
{ "data": "middleName"},
{ "data": "lastName"},
{ "data": "plateNumber"},
{ "data": "timeStamp" },
{
"data": "id",
"render": function (data) {
return `<div class="text-center">
<a href="Customers/upsert?id=${data}" class="btn btn-success text-white" style="cursor:pointer; width:70px;">
Edit
</a>
<a class="btn btn-danger text-white" style="cursor:pointer; width:70px;">
Delete
</a>
</div>`;
}, "width": "40%"
}
],
"language": {
"emptyTable": "No data found"
},
"width": "100%"
});
}
This is in my network tab on page load of Customer
It looks like your DataTable element in customer.js should match up with your Index.cshtml element.
i.e. you should change <table id="dt_load" to be <table id="dt_customers"
Then on your server side, because your route is [Route("api/Customer")], therefore in customer.js, your ajax url should be "url": "/api/customer", instead of "url": "/api/customers",

How to fix added parameter in rest call with ajax?

I'm trying to test Datatables composer with ajax Rest calls to spring RestController. I setup front in wampserver and the back with spring boot.
I'm using the spring tuto to setup the RestController https://spring.io/guides/gs/rest-service/
It works fine, I got Json file while calling the controller. I want to using that resutl and show in Datatables.
The code script.js of the font is :
$(document).ready( function () {
$('#table_id').DataTable( {
"processing": true,
"serverSide": false,
"ajax": {
"url": "http://localhost:8080/greeting",
"type": 'GET',
"dataType": "json",
"data": function (data) {
// console.log(data);
return data = JSON.stringify(data);
}
},
"columns": [
{"data": 'id'},
{"data": 'content'}
]
});
});
html page
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf8" src="script.js"></script>
<meta charset="UTF-8">
<title>Gtreetings</title>
</head>
<h3>Hi, little one </h3>
<body>
<table id="table_id" class="display" style="width:100%">
<thead>
<tr>
<th>id</th>
<th>content</th>
</tr>
</thead>
<tfoot>
<tr>
<th>id</th>
<th>content</th>
</tr>
</tfoot>
</table>
</body>
</html>
I got a weird added parameter {}&=1558786054608
and Cross-Origin Request error on http://localhost:8080/greeting?{}&=1558786054608.
I'm not sure if it is a timestamp, I don't know how to explane this.
First, in your JS script, you have an error in the ajax call, the data means the parameter send not from ajax. here is a correct version of the code.
$(document).ready( function () {
$('#table_id').DataTable({
processing: true,
serverSide: false,
dataType: "json",
ajax: {
url: "http://localhost:8080/greeting",
method: 'GET',
dataSrc: function (json) {
console.log("json",json)
return json;
},
},
columns: [
{data: 'id'},
{data: 'content'}
]
});
});
Second, in the backend on the controller you have to add annotation #CrossOrigin(origins = "*") thus you avoid the error cross-origin.
Finally, Datatable has to have an array in the retune result, and it is not the case in your controller. It returns an object.
I suggest to wrap your object within a list as follows :
#CrossOrigin(origins = "*")
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
public List<Greeting> greeting(#RequestParam(value="name", defaultValue="World") String name) {
List<Greeting> ls = new ArrayList<Greeting>();
ls.add(new Greeting(counter.incrementAndGet(),
String.format(template, name)));
return ls;
}
}
I hope it helps.

ASP.net MVC Ajax DataTable Error 7

Kinda newbie when it comes to ASP.net MVC side of things not sure why I am getting Ajax Error 7 in DataTable
here is my code : for cshtml
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Register new Users</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap
/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/
jquery.dataTables.min.css" />
<link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />
<style>
span.field-validation-error {
color: red;
}
</style>
</head>
<body>
<div style="width:90%; margin:0 auto ">
you are in the Table area
<table id="myDatatable">
<thead>
<tr>
<th>User ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>User Email</th>
<th>Username</th>
<th>Users ImagePath</th>
<th>SSID</th>
</tr>
</thead>
</table>
</div>
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script>
$(document).ready(function () {
var oTable = $('#myDatatable').DataTable({
"ajax": {
"url": '/home/GetUsers',
"type" : "get",
"dataType": "json"
},
"columns": [
{ "data": "Users_ID", "autoWidth": "true" },
{ "data": "Users_Fname", "autoWidth": "true" },
{ "data": "Users_Sname", "autoWidth": "true" },
{ "data": "Users_Email", "autoWidth": "true" },
{ "data": "Users_Usersname", "autoWidth": "true" },
{ "data": "Users_ImagePath", "autoWidth": "true" },
{ "data": "FK_Product_ID", "autoWidth": "true" }
]
})
})
</script>
</body>
</html>
I have tried few stackflow troubleshooting but am not getting anywhere
my file structure name are as follows
under the model folder I have EPOSv3DataModel.edmx
under the home folder I have HomeController.cs file within this
I have the following code :
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to Registration System";
//EPOSv3Entities1 r = new EPOSv3Entities1();
//var data = r.tbl_Users.ToList();
//ViewBag.userdetails = data;
return View();
}
#region Get Users from the database
public ActionResult GetUsers()
{
using (EPOSv3Entities1 entity = new EPOSv3Entities1())
{
// get the data order by firstname
var users = entity.tbl_Users.OrderBy
(a => a.Users_Fname).ToList();
return Json(new { data = users }, JsonRequestBehavior.AllowGet);
}// end of your using statement
}
#endregion
}end of class
}//end of namespace
I was following this video tutorial from: YouTube
and the site where this developer has his code is :ASP.net CRUD DataTable
Very much appreciate your support the table display but does not load any data
also when in URL when I enter the https://localhost/portnumber/Home/GetUsers the ajax error disappears but no loading data.
HELP :(
you can try this
using (EPOSv3Entities1 entity = new EPOSv3Entities1())
{
entity.Configuration.ProxyCreationEnabled = false;
// get the data order by firstname
var users = entity.tbl_Users.OrderBy
(a => a.Users_Fname).ToList();
return Json(new { data = users }, JsonRequestBehavior.AllowGet);
}// end of your using statement
you are using entity framework generated proxy object which might be causing problems in serializing

Kendo UI Grid sortable (and other properties) not working

I'm trying to configure a Kendo grid and I'm having issues when trying to add properties such as sorting, grouping, etc. The grid works until I add the property, then it doesn't display any of the data. I have looked at the documentation on Kendo's site and it looks as if I have everything the same as theirs but obviously I'm nissing something.
Here is the View:
#model ExampleKendoUI.Models.HeaderVm
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div>#Model.Name</div>
#section scripts {
<script>
// Output the data as JSON
var podata = #Html.Raw(Json.Encode(ViewBag.LineItems));
</script>
<div id="poGrid" class="k-content">
<script>
$(document).ready(function () {
$("#poGrid").kendoGrid({
dataSource: {
data: podata
},
// sortable:true, *** Uncommenting this will break the grid ***
columns: [
{
field: "Description",
title: "Desc"
},
{
field: "Quantity",
title: "Quantity"
}
]
});
});
</script>
</div>
}
Here is the controller:
namespace ExampleKendoUI.Controllers
{
public class SampleController : Controller
{
//
// GET: /Sample/
public ActionResult Index(int id)
{
var header = new HeaderVm()
{
Id = id,
Name = "Req ID"
};
var results = new List<PoLineVm>()
{
new PoLineVm()
{
Id = 1,
Description = "Some Product",
Quantity = 1.5
},
new PoLineVm()
{
Id = 2,
Description = "Another Product",
Quantity = 4.0
},
new PoLineVm()
{
Id = 3,
Description = "Last Product",
Quantity = 20
},
};
ViewBag.LineItems = results;
return View(header);
}}}
Here is the _Layout:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
<link href="~/Content/kendo/2012.3.1114/kendo.default.min.css" rel="stylesheet" />
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
#RenderBody()
#Scripts.Render("~/bundles/jquery")
<script src="/scripts/kendo/2012.3.1114/kendo.core.min.js"></script>
<script src="~/Scripts/kendo/2012.3.1114/kendo.data.min.js"></script>
<script src="~/Scripts/kendo/2012.3.1114/kendo.grid.min.js"></script>
#RenderSection("scripts", required: false)
</body>
</html>
You haven't included the required JavaScript files and the JavaScript error means that kendoSortable is missing. Check the documentation for the required JavaScript files: http://docs.kendoui.com/getting-started/javascript-dependencies

Uploadify in MVC3 does not work

Can't get this to do anything. When I click 'Upload File' absolutely nothing happens as well as I don't see any of the flash rendered to the screen. I believe this is somehow related to the jquery, but I am not sure. PLEASE HELP! If someone can mail me a simple VS2010 solution with uploadify working to infinitimods at gmail.com that actually works I'd appreciate even more! Thanks a bunch!
My Layout file:
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link type="text/css" rel="Stylesheet" media="screen" href="/Scripts/uploadify/uploadify.css" />
<script type="text/javascript" src="/Scripts/uploadify/swfobject.js"></script>
<script type="text/javascript" src="/Scripts/uploadify/jquery.uploadify.v2.1.4.min.js"></script>
<script type="text/javascript" src="/Scripts/uploadify/jquery-1.4.2.min.js"></script>
</head>
<body>
#RenderBody()
</body>
</html>
My index file:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<script type="text/javascript">
$(document).ready(function () {
$("#file_upload").uploadify({
'uploader': '~/Scripts/uploadify/uploadify.swf',
'cancelImg': '~/Scripts/uploadify/images/cancel.png',
'buttonText': 'Upload foto',
'script': '/Home/UploadFiles',
'folder': '/Content/upload',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png; *.txt;',
'scriptData': { 'thisGuid': $("input#Id").val() },
'multi': false,
'auto': true,
'onError': function (event, queueID, fileObj, errorObj) {
alert("Error!!! Type: [" + errorObj.type + "] Info [" + errorObj.info + "]");
}
});
$("#btnSave").button().click(function (event) {
$('#file_upload').uploadifyUpload();
});
});
</script>
<input id="file_upload" type="file" />
<input type="button" id="btnSave" value="Upload file" />
<input id="Id" name="Id" type="hidden" value="5168e-yada-yada" />
}
My controller:
public class HomeController : Controller
{
/// <summary>
///
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult Index()
{
return View("Index");
}
/// <summary>
///
/// </summary>
/// <param name="fileData"></param>
/// <param name="form"></param>
/// <returns></returns>
[HttpPost]
public string UploadFile(HttpPostedFileBase fileData, FormCollection form)
{
return "ok";
}
}
Uploadify requires jQuery. This means that you need to include the jQuery script before the uploadify script. If you had looked in your javascript debugging console you would have seen this error.
So, the layout:
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Scripts/uploadify/uploadify.css")" type="text/css" rel="stylesheet" media="screen" />
<script type="text/javascript" src="#Url.Content("~/Scripts/uploadify/swfobject.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/uploadify/jquery-1.4.2.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/uploadify/jquery.uploadify.v2.1.4.min.js")"></script>
</head>
<body>
#RenderBody()
</body>
</html>
The controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase fileData, string thisGuid)
{
if (fileData != null && fileData.ContentLength > 0)
{
var appData = Server.MapPath("~/app_data");
var file = Path.Combine(appData, Path.GetFileName(fileData.FileName));
fileData.SaveAs(file);
}
return Json(new { status = true });
}
}
and the view:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript">
$(document).ready(function () {
$('#file_upload').uploadify({
'uploader': '#Url.Content("~/Scripts/uploadify/uploadify.swf")',
'cancelImg': '#Url.Content("~/Scripts/uploadify/images/cancel.png")',
'buttonText': 'Select photo',
'script': $('form').attr('action'),
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png; *.txt;',
'multi': false,
'auto': false,
'onError': function (event, queueID, fileObj, errorObj) {
alert("Error!!! Type: [" + errorObj.type + "] Info [" + errorObj.info + "]");
}
});
$('form').submit(function () {
$('#file_upload').uploadifySettings('scriptData', { thisGuid: $('#id').val() });
$('#file_upload').uploadifyUpload();
return false;
});
});
</script>
<h2>Index</h2>
#using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input id="id" name="id" type="hidden" value="5168e-yada-yada" />
<input id="file_upload" type="file" name="fileData" />
<input type="submit" value="Upload file" />
}
And if you want to kick the uploading process when the user selects a photo you could get rid of the form and the submit button and set the auto property to true:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript">
$(document).ready(function () {
$('#file_upload').uploadify({
'uploader': '#Url.Content("~/Scripts/uploadify/uploadify.swf")',
'cancelImg': '#Url.Content("~/Scripts/uploadify/images/cancel.png")',
'buttonText': 'Select photo',
'script': $('form').attr('action'),
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png; *.txt;',
'multi': false,
'auto': true,
'scriptData': { thisGuid: $('#id').val() },
'onError': function (event, queueID, fileObj, errorObj) {
alert("Error!!! Type: [" + errorObj.type + "] Info [" + errorObj.info + "]");
}
});
});
</script>
<h2>Index</h2>
<input id="id" name="id" type="hidden" value="5168e-yada-yada" />
<input id="file_upload" type="file" name="fileData" />
Also don't forget to checkout the uploadify documentation to better understand what the different options are used for and also you can see some examples.
You need to work around a bug with asp.net and flash.
This article helped me once: Working around flash cookie bug
Maybe this is a better solution: jquery file upload

Resources