DataTables warning - Requested unknown parameter '0' for row 0, column 0 - c#

I am working with DataTable.js and trying to implement into MVC. I've written code as per below:
View:
<div id="container">
<div id="demo">
<h2>Index</h2>
<table id="myDataTable" class="display">
<thead>
<tr>
<th>ID</th>
<th>Event Name</th>
<th>Event Type</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
#section scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#myDataTable').dataTable({
"bServerSide": true,
"sAjaxSource": "#Url.Action("AjaxHandler","DataTable")",
"bProcessing": true,
"aoColumns": [
{ "sName": "EventID" },
{ "sName": "EventName" },
{ "sName": "EventTypeTitle" }
]
});
});
</script>
}
And Controller:
public ActionResult Index()
{
return View();
}
public ActionResult AjaxHandler(jQueryDataTableParamModel param)
{
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = getAllEvent().Count(),
iTotalDisplayRecords = getAllEvent().Count(),
aaData = getAllEvent()
}, JsonRequestBehavior.AllowGet);
}
private List<EventModel> getAllEvent()
{
List<EventModel> model = new List<EventModel>();
EventModel model1 = new EventModel { EventID = 1, EventName = "Event 1", EventType = 1, EventTypeTitle = "General" };
model1.EventScheduleList = new List<EventScheduleModel> { new EventScheduleModel {EventScheduleID = 1 }, new EventScheduleModel { EventScheduleID = 2 } };
model.Add(model1);
return model;
}
I am getting DataTables warning: table id=myDataTable - Requested
unknown parameter '0' for row 0, column 0. For more information about
this error, please see http://datatables.net/tn/4
As I research about the error I could find that this particular error is occur when data is not in correct manner. but, when I check response, I am getting correct data.
Is it because I have returned more numbers of columns which are used
in View? or Do I send integer value in JSON?
I've attached fiddle link as well:
https://dotnetfiddle.net/MEoqg8

You need to make very small change in you JacaScript code which goes like this, which means instead of using sName you need to use data inside aoColumns array.
<script>
$(document).ready(function () {
$('#myDataTable').dataTable({
"bServerSide": true,
"sAjaxSource": '#Url.Action("AjaxHandler","Home")',
"bProcessing": true,
"aoColumns": [
{
"data": "EventID",
"bSearchable": false,
"fnRender": function (oObj) {
return '<a href=\"Details/' +
oObj.aData[0] + '\">View</a>';
}
},
{ "data": "EventName" },
{ "data": "EventTypeTitle" }
]
});
});
</script>
You can check a fork from your fiddle here : https://dotnetfiddle.net/7sXghO

Related

How to load partial view in <DIV> tag?

I am still learning MVC. I am having problem with Partial View. I have a page with dropdown value. And whenever user choose the value, a partial page with datatable will appear.
Currently, i am thinking of using JQuery load function to load the page into the div tag. But the datatable is not showing. Is there something wrong with my code or is it any better way of doing this? Please help. Thank you.
My View:
#model MVCWeb.Models.DP_Table
#{
ViewBag.Title = "Data Patching";
}
<br />
<h2>#ViewBag.Title</h2>
<br />
<table class="table-striped table-responsive">
<tbody>
<tr>
<td width="40%">
<label class="control-label">Select Table</label>
</td>
<td width="10%">:</td>
<td width="*%">
#Html.DropDownListFor(Model => Model.DPTableID, new SelectList(Model.TableCollection,
"DPTableId", "TableName"), "Please Select", new { #id = "ddTableName", #class = "form-control" })
</td>
</tr>
<tr>
<td><br /></td>
</tr>
<tr>
<td>
<label class="control-label">Select Action</label>
</td>
<td>:</td>
<td>
#Html.DropDownList("Actions", #ViewBag.PatchingActions as List<SelectListItem>,
"Please Select", new { #id = "ddPatchingAction", #class = "form-control", #disabled = "disabled" })
</td>
</tr>
</tbody>
</table>
<br />
<div id="divPatching"></div>
#section scripts{
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script>
var ddTableValue, ddPatchingActionValue;
$('#ddTableName').change(function () {
ddTableValue = $('#ddTableName option:selected').val();
if (ddTableValue) {
$("#ddPatchingAction").prop("disabled", false);
} else {
$("#ddPatchingAction").prop("disabled", true);
}
});
$('#ddPatchingAction').change(function () {
ddPatchingActionValue = $('#ddPatchingAction option:selected').val();
if (ddPatchingActionValue) {
$("#divPatching").load('#Url.Action("GetPartialView", "DataPatching")');
}
});
</script>
}
My Controller:
public PartialViewResult GetPartialView()
{
return PartialView("~/Views/PatchingBatch/Index.cshtml");
}
My Partial View:
<a class="btn btn-success" style="margin-bottom:10px" onclick="AddUserForm('#Url.Action("AddUser", "Account")')"><i class="fa fa-plus"></i> Add New User</a>
<table id="batchTable" class="table-striped table-responsive">
<thead>
<tr>
<th>Username</th>
<th>Name</th>
<th>Email Address</th>
<th>Is Admin</th>
<th></th>
</tr>
</thead>
</table>
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
#section scripts{
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script>
var popup, dataTable;
$(document).ready(function () {
dataTable = $("#batchTable").DataTable({
"ajax": {
"url": "/Account/GetDPUserList",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "Username", "name":"Username" },
{ "data": "Name", "name": "Name" },
{ "data": "Email", "name": "Email" },
{ "data": "IsAdmin", "name": "IsAdmin" },
{
"data": "DPUserID", "render": function (data) {
return "<a class='btn btn-primary btn-sm' onclick=EditUserForm('#Url.Action("UpdateUser", "Account")/" + 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"
},
],
"processing": "true",
"serverSide": "true",
"order": [0, "asc"]
});
});
function AddUserForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: "Add User Account",
height: 250,
width: 300,
close: function () {
popup.dialog('destroy').remove();
}
});
});
}
function EditUserForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: "Update User Account",
height: 410,
width: 300,
close: function () {
popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
if ($(form).valid()) {
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (data) {
if (data.success) {
popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
});
}
return false;
}
function Delete(id) {
if (confirm("Are you sure you want to delete this data?")) {
$.ajax({
type: "POST",
url: '#Url.Action("DeleteUser", "Account")/' + id,
success: function (data) {
if (data.success) {
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
}
)
}
}
</script>
}
My Partial Controller:
public ActionResult Index()
{
return PartialView();
}
[HttpPost]
public ActionResult GetDPUserList()
{
//server side parameter
int start = Convert.ToInt32(Request["start"]);
int length = Convert.ToInt32(Request["length"]);
string searchValue = Request["search[value]"];
string sortColumnName = Request["columns[" + Request["order[0][column]"] + "][name]"];
string sortDirection = Request["order[0][dir]"];
List<DP_User> userList = new List<DP_User>();
using (DBModel db = new DBModel())
{
userList = db.DP_User.ToList<DP_User>();
userList = userList.ToList<DP_User>();
int totalrows = userList.Count();
//search
if (!string.IsNullOrEmpty(searchValue))
{
userList = userList.Where(x => (x.Username != null && x.Username.ToString().ToLower().Contains(searchValue)) ||
(x.Name != null && x.Name.ToString().ToLower().Contains(searchValue)) ||
(x.Email != null && x.Email.ToString().ToLower().Contains(searchValue))).ToList<DP_User>();
}
int totalrowsafterfilter = userList.Count();
//sorting
if (!string.IsNullOrEmpty(sortColumnName) && !string.IsNullOrEmpty(sortDirection))
{
userList = userList.OrderBy(sortColumnName + " " + sortDirection).ToList<DP_User>();
}
//paging
userList = userList.Skip(start).Take(length).ToList<DP_User>();
return Json(new { data = userList, draw = Request["draw"], recordsTotal = totalrows, recordsFiltered = totalrowsafterfilter },
JsonRequestBehavior.AllowGet);
}
}
1-Create One Partial View To Name Of Page
2-Create One Action
public ActionResult YourPage()
{
return PartialView("~/Views/Page.cshtml");
}
3-To Your View Create One div
<div id="MyDiv"></div>
4-Write This Code To script
$(document).ready(function () {
$.get("/Home/YourPage", function (data) {
$('#MyDiv').html(data);
});
});
If you are in ASP.NET core you can use this command
<partial name="_yourPartial" />
it will load the view for you from a method in the controller
if you are in an older version of ASP.NET you can use this older command
#Html.Partial("_yourPartial")
it works the same way, and avoid using jquery
you can also pass a model through it, using the command
#Html.Partial("_yourPartial", new { paramName = "foo" })

Drop down selected value to Edi in MVC

Running MVC application in visual studio. this application based on Timesheet management. i have different project drop down list . i have attached screen shot for your reference
Before Submit :
after if user enter wrong if trying change time looks
Concrete Class :
public void UpdateEmployee(TimeSheetDetails timesheetupdate)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TimesheetDBEntities"].ToString()))
{
SqlCommand cmd = new SqlCommand("Usp_UpdateTimesheet", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#TimeSheetID ",timesheetupdate.TimeSheetID);
cmd.Parameters.AddWithValue("#DaysofWeek", timesheetupdate.DaysofWeek);
cmd.Parameters.AddWithValue("#Hours", timesheetupdate.Hours);
cmd.Parameters.AddWithValue("#Period", timesheetupdate.Period);
cmd.Parameters.AddWithValue("#ProjectID", timesheetupdate.ProjectID);
cmd.Parameters.AddWithValue("#UserID", timesheetupdate.UserID);
cmd.Parameters.AddWithValue("#CreatedOn", timesheetupdate.CreatedOn);
cmd.Parameters.AddWithValue("#TimeSheetMasterID", timesheetupdate.TimeSheetMasterID);
cmd.Parameters.AddWithValue("#TotalHours",timesheetupdate.Hours);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Edit Controller Action :
// GET: Employee/EditEmpDetails/5
public ActionResult EditTimesheet(int id)
{
TimeSheetConcrete EmpRepo = new TimeSheetConcrete();
return View(EmpRepo.TimesheetDetailsbyTimeSheetMasterID().Find(Emp => Emp.TimeSheetID == id));
}
// POST: Employee/EditEmpDetails/5
[HttpPost]
public ActionResult EditTimesheet(int id, EmpModel obj)
{
try
{
TimeSheetConcrete EmpRepo = new TimeSheetConcrete();
EmpRepo.UpdateEmployee(obj);
return RedirectToAction("GetAllEmpDetails");
}
catch
{
return View();
}
}
My View :
#{
ViewBag.Title = "TimeSheet";
Layout = "~/Views/Shared/_LayoutUser.cshtml";
}
<link href="~/Scripts/dataTablesScripts/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="~/Scripts/dataTablesScripts/responsive.bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/dataTablesScripts/jquery.dataTables.min.js"></script>
<script src="~/Scripts/dataTablesScripts/dataTables.bootstrap4.min.js"></script>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">All TimeSheet</div>
<div class="panel-body">
<table id="myTable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<th>TimeSheetMasterID</th>
<th>FromDate</th>
<th>ToDate</th>
<th>TotalHours</th>
<th>CreatedOn</th>
<th>TimeSheetStatus</th>
<th>Comment</th>
<th>Details</th>
<th>Delete</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$("#myTable").DataTable({
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": true, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
"ajax": {
"url": "/AllTimeSheet/LoadTimeSheetData",
"type": "POST",
"datatype": "json"
},
"columnDefs":
[{
"targets": [0],
"visible": false,
"searchable": false
},
{
"targets": [6],
"searchable": false,
"orderable": false
},
{
"targets": [7],
"searchable": false,
"orderable": false
},
{
"targets": [8],
"searchable": false,
"orderable": false
}
],
"columns": [
{ "data": "TimeSheetMasterID", "name": "TimeSheetMasterID", "autoWidth": true },
{ "data": "FromDate", "name": "FromDate", "autoWidth": true },
{ "data": "ToDate", "name": "ToDate", "autoWidth": true },
{ "data": "TotalHours", "name": "TotalHours", "autoWidth": true },
{ "data": "CreatedOn", "name": "CreatedOn", "autoWidth": true },
{ "data": "TimeSheetStatus", "name": "TimeSheetStatus", "title": "Status", "autoWidth": true },
{ "data": "Comment", "name": "Comment", "title": "Comment", "autoWidth": true },
{
"render": function (data, type, full, meta)
{ return '<a class="btn btn-info" href="/AllTimeSheet/Details/' + full.TimeSheetMasterID + '">View</a>'; }
},
{
data: null, render: function (data, type, row) {
if (row.TimeSheetStatus == "Submitted" || row.TimeSheetStatus == "Rejected") {
return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.TimeSheetMasterID + "'); >Delete</a>";
}
else {
return row.TimeSheetStatus;
}
}
},
{
"render": function (data, type, full, meta) { return '<a class="btn btn-info" href="/TimeSheet/Edit/' + full.TimeSheetMasterID + '">View</a>'; }
},
]
});
});
</script>
<script type="text/javascript">
function DeleteData(ID) {
if (confirm("Are you sure you want to delete ...?")) {
DeleteSheet(ID);
}
else {
return false;
}
}
function DeleteSheet(ID) {
// var url = '#Url.Content("~/TimeSheetID")' + "TimeSheet/Delete";
$.post(url, { TimeSheetMasterID: ID }, function (data) {
if (data) {
oTable = $('#myTable').DataTable();
oTable.draw();
}
else {
alert("Something Went Wrong!");
}
});
}
</script>
if user want selected edit mode dropdown selected value ? i am trying many ways i am getting error . please any one give idea to solve this issues

Datatable server side processing c# mvc

Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult LoadData()
{
var draw = Request.Form.GetValues("draw").FirstOrDefault();
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int totalRecord = 0;
using (ACETeaEntities db = new ACETeaEntities())
{
var v = (from item in db.Drinks_Category select item);
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
{
v = v.OrderBy(sortColumn + " " + sortColumnDir);
}
totalRecord = v.Count();
var data = v.Skip(skip).Take(pageSize).ToList();
return Json(new { draw = draw, recordsFilterd = totalRecord, recordsTotal = totalRecord, data = data }, JsonRequestBehavior.AllowGet);
}
}
}
View:
<script src="~/Scripts/jquery-1.7.2.js" ></script>
<script src="~/Scripts/DataTables/jquery.dataTables.js" ></script>
<link rel="stylesheet" type="text/css" href="~/Content/DataTables/css/jquery.dataTables.css">
<script>
$(document).ready(function () {
$('#example').dataTable({
"processing": true,
"serverSide": true,
"filter": true,
"ordermulti": false,
"ajax": {
"url": "/Home/LoadData",
"type": "POST",
"dataType": "json"
},
"columns": [
{ "data": "Name_category", "autoWidth": true },
{ "data": "Id_category", "autoWidth": true },
{ "data": "Parent", "autoWidth": true }
]
});
});
</script>
<div style="margin:30px;">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr style="text-align:left;">
<th>Id</th>
<th>Name</th>
<th>Parent</th>
</tr>
</thead>
<tfoot>
<tr style="text-align:left;">
</tr>
</tfoot>
</table>
</div>
My code bugs at: v = v.OrderBy(sortColumn + " " + sortColumnDir);
Can someone help me fix it?
When using the OrderBy method you need to pass the column you want to sort by as a property and use a different method for defining the direction
For example:
v = v.OrderBy(i => i.myColumn);
v = v.OrderByDescending(i => i.myColumn);
Since you are getting your parameters as a string, you have two options:
1) You can build your function first before passing it as well as define your direction
For example:
if (sortColumn == "myColumn")
{
myOrderByFunc = i => i.myColumn;
}
elseif (sortColumn == "myOtherColumn")
{
myOrderByFunc = i => i.myOtherColumn;
}
if (direction == "asc")
{
v = v.OrderBy(myOrderByFunc);
}
elseif (direction == "desc")
{
v = v.OrderByDescending(myOrderByFunc);
}
2) You can use the System.Linq.Dynamic library available here to use strings directly in the linq query (as you are doing now)
Note that you can also try the more updated library System.Linq.Dynamic.Core which does support OrderBy and also ThenBy.

DataTables warning: table id={id} - Ajax error

i am trying to bind json to table using datatable
here is my code Html
<table class="table table-bordered table-striped" id="dataTables-1">
<thead>
<tr>
<th>Customer Site Id</th>
<th>Customer Product name</th>
<th>Start Date Time</th>
<th>Stop Date Time</th>
<th>Upload</th>
<th>Download</th>
</tr>
</thead>
<tbody></tbody>
</table>
and here is script of datatable
<script type="text/javascript">
$("#btnFilter").click(function () {
//var tab = $("#Tab").val().length;
//var fromDate = $("#FromModel").val();
//var toDate = $("#ToDate").val();
CreateTableUsage();
});
function CreateTableUsage() {
$('#dataTables-1').DataTable({
searching: false,
'bAutoWidth': false,
sAjaxSource: '#Url.Action("Filter") + ?tab=' + encodeURI($('#Tab').val()) + encodeURI($('#FromModel').val()) + encodeURI($('#ToDate').val()),
aoColumns: [
{ "sName": "SiteRefId", "bSortable": false },
{ "sName": "CustomerServiceRefId", "bSortable": false },
{ "sName": "StartTimeUtc", "bSortable": false },
{ "sName": "StopTimeUtc", "bSortable": false },
{ "sName": "CallingStationId", "bSortable": false },
{ "sName": "IpAddress", "bSortable": false }]
});
}
</script>
here is code BackEnd
public ActionResult Filter(string tab, string FromDate, string ToDate)
{
return Json(new { aaData = lUsage.Select( x => new object[] { x.SiteRefId, x.CustomerServiceRefId, x.StartTimeUtc , x.StopTimeUtc, x.CallingStationId, x.IpAddress}).ToList() }, JsonRequestBehavior.AllowGet);
}
when action return the json to view, it raise a error of datatable
DataTables warning: table id={id} - Ajax error
I think you should try to do like bellow on one of your Datatable Option.
$('#example').dataTable( {
"destroy": true
} );
It caused by reinitialising datatable as you see on the error message.
The destroy option is for it.

Icheck style is not applied in ajax databind in datatable

I am using iCheck plug-in with datatable.js in my web application.
I use a ajax request to databind this table.
Please see my code below.
Html
<table id="tblCountry" class="table table-striped table-bordered table-hover table-highlight table-checkable"
data-display-rows="10"
data-info="true"
data-search="true"
data-paginate="true" >
<thead>
<tr>
<th class="checkbox-column" style="min-width: 50px;">
<input id="thCheckBox" type="checkbox" class="icheck-input" />
</th>
<th>Id</th>
<th style="min-width: 100px;">Country</th>
</tr>
</thead>
</table>
Script
ajaxUrl = '#Url.Action("GetTestCountryList", "Invoice")';
dtTable = $("#tblCountry").dataTable({
sAjaxSource: ajaxUrl,
aoColumns: [
{
"sClass": "checkbox-column",
bSortable: false,
"mRender": function (data, type, full) {
return '<input type="checkbox" onclick="check(this)" class="icheck-input">';
}
},
{ sTitle: "Id", bSortable: false, bVisible: false, },
{ sTitle: "Name", bSortable: true, },
],
});
Source
public ActionResult GetTestCountryList()
{
List<Country> lstCountry = new List<Country>();
lstCountry.Add(new Country { Id = 1, Name = "India" });
lstCountry.Add(new Country { Id = 2, Name = "USA" });
lstCountry.Add(new Country { Id = 3, Name = "France" });
lstCountry.Add(new Country { Id = 4, Name = "Germiny" });
lstCountry.Add(new Country { Id = 5, Name = "Britan" });
return Json(new
{
aaData = lstCountry.Select(e => new string[]
{
"",
e.Id.ToString(),
e.Name
}).ToArray()
}, JsonRequestBehavior.AllowGet);
}
My problem is the check box style is only applied in the header not applied in the rows. Is there any fault in my code?
You need to call icheck from the datatables DrawCallBack - I had the same issue...
$('.ajax-datatable').dataTable({
responsive: false,
order: [],
sPaginationType: "simple_numbers",
bJQueryUI: true,
bProcessing: false,
bServerSide: true,
bStateSave: true,
sAjaxSource: $('.ajax-datatable').data('source'),
"columnDefs": [
{ "orderable": false, "targets":[$('.ajax-datatable').data('targets')]}
],
"fnPreDrawCallback": function() {
$.blockUI({ message: '<img src="<%= asset_path 'ajax-loader.gif'%>" />',css: { backgroundColor: 'none', border: '0px'} });
return true;
},
"fnDrawCallback": function() {
$.unblockUI();
icheck();
}
});
add a checked attribute like this
return '<input type="checkbox" onclick="check(this)" class="icheck-input" checked>';

Categories

Resources