ASP.net MVC Ajax DataTable Error 7 - ajax

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

Related

C# jQuery Ajax Datatables ASP.NET Core 5 MVC

I am attempting to implement ASP.NET Core SignalR. I am looking for assistance. The project is located at: https://github.com/Talsiter/AspNetCore-SignalR-SqlTableDependency
The issue that I am running into is when a datatable is being populated from jQuery AJAX, no data is being populated into the view.
Items model (Item.cs)
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace InAndOut.Models
{
public class Item
{
[Key]
public int Id { get; set; }
public string Borrower { get; set; }
public string Lender { get; set; }
[DisplayName("Item name")]
public string ItemName { get; set; }
}
}
Items view (Index.cshtml)
#model IEnumerable<InAndOut.Models.Item>
<div class="container p-3">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<div class="card-body">
<table id="myTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>Id</th>
<th>Item Name</th>
<th>Borrower</th>
<th>Lender</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
#section Scripts {
#* These Scrips are Required *#
<script src="~/js/signalr/dist/browser/signalr.js"></script>
#*This one gives me an error of "ItemsHub undefined"*#
#*<script src="~/js/items01.js"></script>*#
#* This gives me an error "DataTable is not a function"
This probably requires the *#
<link href="//cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css" rel="stylesheet" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="~/js/items03.js"></script>
}
Items JS file (items03.js):
// This is from:
//https://stackoverflow.com/questions/51764211/jquery-datatable-loading-using-ajax-asp-net-mvc
// Does Not Display any data
function getAllMessages() {
$('#myTable').DataTable({
processing: true,
serverSide: false,
ordering: true,
paging: true,
searching: true,
columns: [
{ title: "Id" },
{ title: "ItemName" },
{ title: "Borrower" },
{ title: "Lender" },
{ title: "View Data" }
],
columns: [
{ data: "Id" },
{ data: "ItemName" },
{ data: "Borrower" },
{ data: "Lender" },
{
data: null,
defaultContent: "<button class='tblview'>View Id</button><button class='tblDelete'>Delete</button>"
}
],
ajax: {
"url": "/Item/GetItems",
"type": "GET",
"dataSrc": ''
},
"columnDefs": [
{
"targets": 0,
"visible": false
}
]
});
}
Item controller (ItemController.cs):
// This was updated from:
// https://stackoverflow.com/questions/51705732/jquery-datatable-ajax-no-data-available-mvc
public IActionResult GetItems()
{
var items = new List<Item>
{
new Item { Id = 1, ItemName = "Computer", Borrower = "Justin", Lender = "Don"},
new Item { Id = 2, ItemName = "Mouse", Borrower = "Mark", Lender = "Susan"},
new Item { Id = 3, ItemName = "Monitor", Borrower = "Mark", Lender = "Joe"},
new Item { Id = 4, ItemName = "Keyboard", Borrower = "Candace", Lender = "Angela"},
new Item { Id = 5, ItemName = "Printer", Borrower = "Mike", Lender = "Watson"},
};
// JsonRequestBehavior requires Microsoft.AspNet.MVC
// I do not want to reference it. I want to use Microsoft.AspNetCore.Mvc
//return Json(items, JsonRequestBehavior.AllowGet);
// I referenced this to mitigate the above issue
// https://stackoverflow.com/questions/38578463/asp-net-core-the-name-jsonrequestbehavior-does-not-exist-in-the-current-cont
//return Json(items);
// Error: Cannot read property 'style' of undefined
// This was another option
//return Json(items, new Newtonsoft.Json.JsonSerializerSettings());
// Error: Cannot read property 'style' of undefined
// This seems to be returning the correct data format
// Now the data just is not being displayed in the view
// My error seems to be in the JavaScript
return Json(new { data = items });
}
After many attempts, this is about the closest that I am able to get. While debugging the site, I do not receive any errors, but the mock data does not appear in the items view.
I am suspecting that my issue is in the Items JS file in the getAllMessages() method. I am just not sure how to fix it.
The naming convention for response in asp.net core is camel case instead of pascal case. Also you need remove "dataSrc": ''.
Change like below:
columns: [
{ data: "id" },
{ data: "itemName" },
{ data: "borrower" },
{ data: "lender" },
{
data: null,
defaultContent: "<button class='tblview'>View Id</button><button class='tblDelete'>Delete</button>"
}
],
ajax: {
"url": "/Item/GetItems",
"type": "GET",
//"dataSrc": ''
},

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.

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

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>

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

Resources