Ajax in MVC Page is not consuming a method in Controller - ajax

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",

Related

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>

Spring boot thymeleaf and datatables delete data

i'm learning spring boot with datatables. and now im success show data from MySQL to jquery datatables. and now im create CRUD, but my problem on this learning is delete data.
i'm understand with only table bootstrap create CRUD without datatables :
<table class="table table-striped">
<tr>
<th>Id</th>
<th>Product Id</th>
<th>Name</th>
<th>Price</th>
<th>Delete</th>
</tr>
<tr th:each="product : ${products}">
<td th:text="${product.id}">Id</td>
<td th:text="${product.productId}">Product Id</td>
<td th:text="${product.name}">descirption</td>
<td th:text="${product.price}">price</td>
<td><a th:href="${'/product/delete/' + product.id}">Delete</a></td>
</tr>
</table>
easy only declare local variable thymeleaf on my html.
how delete data from datatables with confirmation dialog ?
this my code datatables :
$(document).ready (function() {
var table = $('#productsTable').DataTable({
"sAjaxSource": "/api/products",
"sAjaxDataProp": "",
"order": [[ 0, "asc" ]],
"columns": [
{ "mData": "id"},
{ "mData": "name" },
{ "mData": "price" },
{ "mData": "productId" },
{ "mData": "version" },
{
data: null,
defaultContent: 'Delete',
orderable: false
}
]
});
$('#btnDelete').on( 'click', 'a.remove', function (e) {
e.preventDefault();
editor.remove( $(this).closest('tr'), {
title: 'Delete Product',
message: 'Are you sure you wish to delete this data ?',
buttons: 'Delete'
} );
} );
});
products.html
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<title>Latihan Spring Boot</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="/js/product.js"></script>
<link rel="stylesheet" href=
"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/css/jquery.dataTables.min.css">
</head>
<body>
<div class="container">
<h1 align="center">Products Table</h1>
<p><a class="btn btn-primary">Add Product</a></p>
<table id="productsTable" class="display">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Price</th>
<th>Product ID</th>
<th>Version</th>
<th></th>
</tr>
</thead>
</table>
</div>
</body>
</html>
Try using jQuery confirm().
Update your code like so
$('#btnDelete').on( 'click', 'a.remove', function (e) {
e.preventDefault();
if(!confirm("Sure you want to delete!")){
return false;
}
editor.remove( $(this).closest('tr'), {
title: 'Delete Product',
message: 'Are you sure you wish to delete this data ?',
buttons: 'Delete'
} );
} );
});

Datatables Handlebars Use of undefined constant

I am working on a a page to display a datatables with row details. I have used exactly the info on the website as follow:
#extends('layouts.app')
#section('style')
<!-- CSS -->
<!-- Select2 -->
<link href="{{ asset('/plugins/select2/select2.min.css') }}" rel="stylesheet" type="text/css" />
<!-- DataTables -->
<link rel="stylesheet" href="{{ asset('/plugins/datatables/dataTables.bootstrap.css') }}">
#stop
#section('scriptsrc')
<!-- JS -->
<!-- Select2 -->
<script src="{{ asset('/plugins/select2/select2.full.min.js') }}" type="text/javascript"></script>
<!-- DataTables -->
<script src="{{ asset('/plugins/datatables/jquery.dataTables.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('/plugins/datatables/dataTables.bootstrap.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('/plugins/datatables/handlebars.js') }}"></script>
#stop
#section('content')
<!-- table widget -->
<div class="box box-info">
<div class="box-header">
<i class="fa fa-cloud-download"></i>
<h3 class="box-title">Employee List</h3>
<div class="box-tools pull-right">
<button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
</div><!-- /.box-tools -->
</div>
<div class="box-body">
<table id="employeeTable" class="display table-bordered table-hover" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>ID</th>
<th>Manager name</th>
<th>Name</th>
<th>Manager ID</th>
<th>Is Manager</th>
<th>Region</th>
<th>Country</th>
<th>Domain</th>
<th>Subdomain</th>
<th>Management Code</th>
<th>Job role</th>
<th>Type</th>
</tr>
</thead>
</table>
<script id="details-template" type="text/x-handlebars-template">
<table class="extra_info display table-bordered table-hover" cellspacing="0" width="50%">
<tr>
<td>Full name:</td>
<td>{{ name }}</td>
</tr>
</table>
</script>
</div>
</div>
#stop
#section('script')
<script>
$(document).ready(function() {
var employeeTable;
var template = Handlebars.compile($("#details-template").html());
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
employeeTable = $('#employeeTable').DataTable({
serverSide: true,
processing: true,
ajax: {
url: "{!! route('ajaxlistemployee') !!}",
type: "POST"
},
columns: [
{
"className": 'details-control',
"orderable": false,
"searchable": false,
"data": null,
"defaultContent": ''
},
{ data: 'id', name: 'employee.id'},
{ data: 'manager_name', name: 'manager.name'},
{ data: 'name', name: 'employee.name'},
{ data: 'manager_id', name: 'employee.manager_id'},
{ data: 'is_manager', name: 'employee.is_manager'},
{ data: 'region', name: 'employee.region'},
{ data: 'country', name: 'employee.country'},
{ data: 'domain', name: 'employee.domain'},
{ data: 'subdomain', name: 'employee.subdomain'},
{ data: 'management_code', name: 'employee.management_code'},
{ data: 'job_role', name: 'employee.job_role'},
{ data: 'employee_type', name: 'employee.employee_type'},
],
columnDefs: [
{
"targets": [1, 4, 5], "visible": false, "searchable": false
}
],
order: [[2, 'asc']]
} );
// Add event listener for opening and closing details
$('#employeeTable tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = employeeTable.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
console.log(row.data());
row.child( template(row.data()) ).show();
tr.addClass('shown');
}
});
} );
</script>
#stop
In the script id details-template that is called, if I use {{ name }}, I get the error Use of undefined constant. But if I put some simple text instead, then everything works (but I don't get my data in this row details of course.
I have checked row.data in the console log and I have all the data available.
What is wrong?
Thanks.

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

Anti Forge Token and Ajax JSON Post Does not Work

I am running MVC3, .Net 4 and VS2010. I have following sample project to illustrate the problem.
My controller code
namespace AntiForgeAjaxTest.Controllers
{
public class IndexController : Controller
{
public ActionResult Index()
{
MyData d = new MyData();
d.Age = 20;
d.Name = "Dummy";
return View(d);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(MyData data)
{
NameValueCollection nc = Request.Form;
return View(data);
}
protected override void ExecuteCore()
{
base.ExecuteCore();
}
}
}
My view and JavaScript code
#model AntiForgeAjaxTest.Models.MyData
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
#using (Html.BeginForm("Index", "Index"))
{
#Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>#Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
alert(JSON.stringify(myObject));
$.ajax({
type: 'POST',
url: '/Index/Index',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(myObject),
success: function (result) {
alert(result);
},
error: function (request, error) {
alert(error);
}
});
});
});
</script>
</body>
</html>
Here I have 2 buttons, the first one triggers form post, the second one triggers Ajax post. The form post works fine, but the Ajax one does not, the server complains A required anti-forgery token was not supplied or was invalid. even though I have included the token in my JSON already.
Any idea what is wrong with my code?
This code works.
#model AntiForgeAjaxTest.Models.MyData
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
#using (Html.BeginForm("Index", "Index"))
{
#Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>#Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
post();
});
});
function post() {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
$.post('/Index/Index/', myObject);
}
</script>
</body>
</html>

Resources