Hope that someone can help me with this.
this is my Controller
namespace PruebaBusquedaRun.Controllers
{
public class TestController : Controller
{
MandatosModel md = new MandatosModel();
// GET: Test
public ActionResult Index()
{
return View();
}
public ActionResult TestDataTable(string run)
{
List<MandatosModel> lmm = new List<MandatosModel>();
DataSet ds = new DataSet();
Int64 asd = Convert.ToInt64(run);
Conexion.ConexionOra conexora = new Conexion.ConexionOra();
ds = conexora.getMandatosPorRun(asd);
foreach (DataRow dr in ds.Tables[0].Rows)
{
lmm.Add(new MandatosModel
{
FOLIO = Convert.ToInt64(dr["FOLIO"]),
IDCAJA = Convert.ToInt64(dr["IDCAJA"]),
NOMBRES = dr["NOMBRES"].ToString(),
A_PATERNO = dr["A_PATERNO"].ToString(),
A_MATERNO = dr["A_MATERNO"].ToString(),
CORREO = dr["CORREO"].ToString()
});
}
return Json(new { data = lmm }, JsonRequestBehavior.AllowGet);
}
}
}
And Here is my View
<div style="width:90%; margin:0 auto;">
#using (Html.BeginForm("TestDataTable", "Test", FormMethod.Post))
{
<br />
<input type="text" id="run" name="run" required />
<button type="button" id="boton">Click Me!</button>
<input type="submit" name="asd" value="Buscar Mandatos" />
<br />
<br />
}
<table id="myTable">
<thead>
<tr>
<th>Folio</th>
<th>Nombres</th>
<th>Apellido Paterno</th>
<th>Apellido Materno</th>
<th>Correo</th>
</tr>
</thead>
</table>
</div>
<style>
tr.even {
background-color: #F5F5F5 !important;
}
</style>
#* Load datatable css *#
<!--<link href="//cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css"
rel="stylesheet" />-->
<link href="~/Content/DataTable/jquery.dataTables.css" rel="stylesheet" />
#* Load datatable js *#
#section Scripts{
<!--<script src="//cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js">
</script>-->
<script src="~/Scripts/DataTable/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#myTable').DataTable({
"ajax": {
"url": "/Test/TestDataTable",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "FOLIO", "autoWidth": true },
{ "data": "NOMBRES", "autoWidth": true },
{ "data": "A_PATERNO", "autoWidth": true },
{ "data": "A_MATERNO", "autoWidth": true },
{ "data": "CORREO", "autoWidth": true }
]
});
});
</script>
}
The main thing that i want to do is to pass a parameter to the TestDataTable method (run) and display the data in the DataTable, in the current state i'm able to execute my procedure and get all the data that i want, but after brings the data it does not return the view with the table, it returns only the plain data.
Sorry for the mistakes and my poor english.
Please help :(
i use a web api , i send my data like this
ajax: {
url: _json,
type: "GET"
},
so in your _json is url + parameters
/Test/TestDataTable?run=demo
--
you need i think is, ajax calling your controller
public JsonResult TestDataTable(string run)
{
try
{
//code
}
catch (Exception ex)
{
return Json(ex.Message);
}
}
some ajax like this.
$.ajax({
cache: !1,
url: '#Url.Action("TestDataTable", "TestController")',
async: !1,
data: { run: demo.val() },
success: function (e) { // data for datatables },
error: function (e, c, t) { alert(e.responseText) }
});
Related
I'm trying to implement datatables to my MVC ASP.NET Core with MySql project so i followed a step-by-step tutorial but i can't fix this error:
" DataTables warning: table id=tblCustomers - Requested unknown parameter 'CustomerID' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4 "
Here's my HTML View page:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style type="text/css">
body {
font-family: Arial;
font-size: 10pt;
}
</style>
</head>
<body>
<div style="width: 500px">
<table id="tblCustomers" cellpadding="0" cellspacing="0" border="1" style="border-collapse:collapse">
<thead>
<tr>
<th>Customer Id</th>
<th>Name</th>
<th>City</th>
<th>Country</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
});
function OnSuccess(response) {
$("#tblCustomers").DataTable(
{
bLengthChange: true,
lengthMenu: [[5, 10, -1], [5, 10, "All"]],
bFilter: true,
bSort: true,
bPaginate: true,
data: response,
columns: [{ 'data': 'CustomerID' },
{ 'data': 'ContactName' },
{ 'data': 'City' },
{ 'data': 'Country' }]
});
};
</script>
</body>
</html>
and here is my Controller:
public class HomeController : Controller
{
private DBCtx Context { get; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult AjaxMethod()
{
var customers = Context.Customers.ToList();
return Json(JsonConvert.SerializeObject(customers));
}
}
My AjaxMethod is returning:
Newtonsoft.Json.JsonConvert.SerializeObject returned "[{"CustomerID":1,"ContactName":"Lucas","City":"Jundiai","Country":"Brasil"},{"CustomerID":2,"ContactName":"Vitoria","City":"Jundiai","Country":"Brasil"},{"CustomerID":3,"ContactName":"Soutto","City":"Jundiai","Country":"Brasil"}]" string
First you need to change your AjaxMethod to :
[HttpPost]
public IActionResult AjaxMethod()
{
var customers = Context.Customers.ToList();
return Json(customers);
}
Then in your OnSuccess function, change it to:
function OnSuccess(response) {
$("#tblCustomers").DataTable(
{
bLengthChange: true,
lengthMenu: [[5, 10, -1], [5, 10, "All"]],
bFilter: true,
bSort: true,
bPaginate: true,
data: response,
columns: [{ 'data': 'customerID' },
{ 'data': 'contactName' },
{ 'data': 'city' },
{ 'data': 'country' }]
});
The columns's first letter needs to be lowercase.
Test result:
I am new to datatables. I am trying to incorporate datatable into an existing ASP.NET MVC application. Below is my Index.cshtml page. I tried to incorporate datatable in this code:
<table id="BookAssignmentTable" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Book</th>
<th>Office</th>
<th>Group</th>
<th>Updated By</th>
<th>Updated On</th>
</tr>
</thead>
</table>
<link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
#section scripts{
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function () {
dataTable = $("#BookAssignmentTable").DataTable({
"ajax": {
"url": "/BookAssign/GetData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Book" },
{ "data": "Office" },
{ "data": "Group" },
{ "data": "UpdatedBy" },
{ "data": "UpdatedOn" },
{
"data": "ID", "render": function (data) {
return "<a class='btn btn-default btn-sm' onclick=PopupForm('#Url.Action("StoreOrEdit", "bookAssignment_new")/" + data + "')><i class='fa fa-pencil'></i>Edit</a> <a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete(" + data + ")><i class='fa fa-trash'></i>Delete</a>";
},
"orderable": false,
"searchable": false,
"width" : "150px"
}
],
"language": {
"emptyTable" : "No data found please click on <b>Add New </b> Button"
}
});
});
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen : true,
resizable : false,
title : 'Fill Book Assignment Details',
height : 500,
width : 700,
close: function () {
Popup.dialog('destroy').remove();
}
});
});
}
</script>
Below is my BookAssignController:
public ActionResult GetData()
{
using (ACREmployeeEntities db= new ACREmployeeEntities())
{
List<bookAssignment_new> bookList = db.bookAssignment_new.ToList<bookAssignment_new>();
return Json(new { data = bookList }, JsonRequestBehavior.AllowGet);
}
}
This is in my route.config file:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "BookAssign", action = "Index", id = UrlParameter.Optional }
);
}
When I run my code, I see this URL, but I don't see any to data.
https://localhost:44374/BookAssign/Index
When I changed the url to
https://localhost:44374/BookAssign/getdata
the debugger stops at the getData method in the controller and returns the correct data. I am not sure what am I don't wrong and why I don't see any data.
Below is the screenshot:
For the first time appearance of .cshtml, you could do the following process:
First you should add <tbody></tbody> behind your <thead></thead> section.
In <tbody></tbody> section, you add a loop like this:
#for(var i = 0; i < yourData.ItsLength; i++)
{
<tr>
<td>yourData[i].YourFirstAttribute</td>
<td>yourData[i].YourSecondAttribute</td>
<td>yourData[i].YourThirdAttribute</td>
</tr>
}
P/S: I recommend you put your js script separately outside .cshtml file.
I am trying to use a datatable and was wondering what i am doing wrong its just stuck on loading and showing waiting to start. This is on my activity controller and the LoadGridData function is called from the scripts below in my index.cshtml.
public ActionResult LoadGridData()
{
// Getting all Customer data
var data = GetAllActivityHeader();
return Json(new { data = data });
}
Here is my GetallActivityHeader function
public async Task<ActionResult<List<ActivityHeader>>> GetAllActivityHeader()
{
return await _activityRepo.GetAllActivityHeader();
}
This is my repositry method which is called above.
public async Task<List<ActivityHeader>> GetAllActivityHeader()
{
using (IDbConnection conn = Connection)
{
if(conn.State == ConnectionState.Closed)
conn.Open();
var result = await conn.QueryAsync<ActivityHeader>("GetActivityHeader");
return result.ToList();
}
}
In My Layout I have the following scripts
#section Scripts{
<script src="//cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js">
</script>
<script>
$(document).ready(function () {
$('#myTable').DataTable({
"ajax": {
"url": "/Activity/LoadGridData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Name", "autoWidth": true },
{ "data": "Description", "autoWidth": true },
{ "data": "Phone", "autoWidth": true },
{ "data": "EmployeeName", "autoWidth": true },
{ "data": "SOP", "autoWidth": true },
{ "data": "Status", "autoWidth": true }
]
});
});
</script>
Html
<div class="container">
<br />
<div style="width:90%; margin:0 auto;">
<table id="myTable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Phone</th>
<th>EmployeeName</th>
<th>SOP</th>
<th>Status</th>
</tr>
</thead>
</table>
</div>
But when i debug the code i am getting the following issue. Also for some reason my edit and delete buttons are not showing I persume i need to code those before they show. Is there any better components for working with datatables and asp.net core?.
And also here is what my view is showing
Edit 1
Ok so i made the method async and that worked and there data their but its still saying no data in the datatable
public async Task<ActionResult> LoadGridData()
{
// Getting all Customer data
var data = await GetAllActivityHeader();
return Json(new { data = data });
}
Finally this is my class obv I dont want to display all in the datatable so I just used the column headers i wanted or is that not how datatables work?.
I have a modal with input fields, i want to be able to capture user inputs in my controller action insert same into the database and display it datatable at the same time without reloading the page.
My Modal Code:
#using (Html.BeginForm("AddVisitEntries", "Consultant", FormMethod.Post, new { #id = "frmPatientRecord", #class = "col-xs-12" }))
{
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
<label id="patientRegNo" class="control-label col-md-2">RegNo:</label>
<div class="col-md-10">
<input type="text" value="" id="patientRegNo" name="patientRegNo" class="form-control" />
</div>
</div>
<div class="form-group">
<label id="appointmentDate" class="control-label col-md-2">Date:</label>
<div class="col-md-10">
<div class='input-group date' id='datetimepicker'>
<input type='text' class="form-control datetimepicker" id="appointmentDate" name="appointmentDate" />
<span class="input-group-addon datetimepicker-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>
}
My Action Method:
[Authorize(Roles = "Consulting")]
public JsonResult InsertPatientAppointment(string patientRegNo, string appointmentDate)
{
if (patientRegNo != null)
{
//Insert record here
//retrieves records here and pass it to the below function
var data = Newtonsoft.Json.JsonConvert.SerializeObject(approveList);
return Json(data);
return Json(new { s = "Record inserted successfully!" });
}
else
{
return Json(new { f = "Insertion failed, please try again later!" });
}
}
My Ajax function:
<script type="text/javascript">
$(document).ready(function () {
var table = $("#tblAppointment").DataTable();
$("#saveButton").click(function () {
$.ajax({
url: '/Consultant/InsertPatientAppointment/',
type: "POST",
data: JSON.stringify({ appointmentDate: $("#appointmentDate"),
patientRegNo: $("#patientRegNo").val(), }),
cache: false,
dataType: "json",
success: function (_data) {
$(".spina").hide();
if (_data.f !== undefined) {
swal({
title: "Failed!",
text: _data.f,
type: "info"
});
table.clear().draw();
return false;
}
else {
swal({
title: "Success!",
text: _data.s,
type: "success"
});
}
var arr = $.map(JSON.parse(_data), function (el) { return el
});
//console.log(arr);
if (arr.length === 0) {
swal({
title: "No Record Found!",
text: _data.f,
type: "info"
});
table.clear().draw();
return false;
}
table.clear();
table.destroy();
$('#tblAppointment').dataTable({
data: arr,
columns: [
{ "data": "PatientRegNo" },
{ "data": "AppointmentDate" },
],
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel',
{
extend: 'pdfHtml5',
orientation: 'Portriat',
pageSize: 'A4'
}
]
});
table = $("#tblAppointment").DataTable();
}
});
});
});
</script>
My modal displays well, but each time i enter input and click on the save button, the values in the controller action are always null, i want to be able to send user input to the controller action, insert and displays same on datatable without reloading the page, any assistance will be appreciated.
What happens is that, you need to model your data as the expected JSON you're posting.
In the following example, I created the type myType with the properties you show on your example and the json is parsed in to the correct type with the properties populated as you expect.
You can read more here Call a Web API From a .NET Client (C#), although I would say that it works not only from a .NET client, but any client..
You can also check this link here with some examples too:
How to receive JSON as an MVC 5 action method parameter
[HttpPost]
public JsonResult InsertPatientAppointment(myType myType)
{
return new JsonResult(new
{
myType.patientRegNo,
myType.appointmentDate
});
}
public class myType {
public string patientRegNo { get; set; }
public string appointmentDate { get; set; }
}
Tested myself with postman.. it works.
I also tried your implementation and was null indeed.
Hope it helps.
I'm new to MVC and Jquery. Trying to use jtable, but nothing happens when loading page.
This is my view.
<link href="~/scripts/jtable.2.4.0/themes/metro/blue/jtable.css"
rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="~/scripts/jtable.2.4.0/jquery.jtable.js">
</script>
#using (Html.BeginForm("Upload", "Hotels", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div id="HotelsTable"> </div>
<script type="text/javascript">
$(document).ready(function () {
//Prepare jtable plugin
$('#HotelsTable').jtable({
title: 'List of Hotels',
paging: true,
pageSize: 10,
sorting: true,
defaultSorting: 'Name ASC',
actions: {
listAction: '#Url.Action("HotelsList")'
},
fields: {
Hotel1: {
title: 'Region',
width: '10%'
},
Hotel2: {
title: 'Hotel',
list: false,
width: '10%'
},
Hotel3: {
title: 'Desde',
type: 'date',
displayFormat: 'yy-mm-dd',
width: '8%',
list: false
},
Hotel4: {
title: 'Hasta',
type: 'date',
displayFormat: 'yy-mm-dd',
width: '8%'
},
Hotel5: {
title: 'Comentarios',
width: '8%',
}
}
});
//Load person list from server
$('#HotelsTable').jtable('load');
});
</script>
}
</body>
</html>
This is my control:
[HttpPost]
public JsonResult HotelsList()
{
try
{
List<Models.Models.HotelElem> hotels =
db.Database.Fetch<Models.Models.HotelElem>("SELECT * FROM Hotels");
return Json(new { Result = "OK", Records = hotels });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
While debugging it doesn't even go my HotelList() method. Need some help, what could it be?
Thanks!
Found solution! Maybe will be useful for someone.
Forgot to add
<script src="~/scripts/jquery-1.9.1.min.js"></script>
<script src="~/scripts/jquery-ui-1.9.2.min.js"></script>
...)