JsonRequestBehaviour.AllowGet Not Working - datatables

i am working for JQuery Datatables server side. While creating the json object, to return back, it doesn't allow JsonRequestBehaviour.AllowGet. If code is exactly same what below is, then i am not able to get data in client side.
HTML :
<table class="table table-striped table-bordered table-hover" id="EmployeeTable">
<thead>
<tr>
<th>LastName</th>
</tr>
</thead>
<tbody></tbody>
</table>
JQuery:
$('#EmployeeTable').DataTable({
"processing" : true, // for show progress bar
"serverSide" : true, // for process in server side
"filter" : false, // to disable search box
"orderMulti" : false,// for disable multiple columns at once
"ajax" : {
"url" : "/Employee/GetEmployeeDataTable",
"type" : "post",
"datatype" : "json"
},
"columns" : [
{ "data": "LastName", "orderable": true }
]
});
Server Side:
[HttpPost]
public ActionResult GetEmployeeDataTable()
{
// Get Parameters
//get start(paging start index) and length(page size for paging)
var draw = Request.Form["draw"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault();
var length = Request.Form["length"].FirstOrDefault();
//get sort column values
var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault()+"][name]"].FirstOrDefault();
var sortColumnDir = Request.Form["order[0][dir]"].FirstOrDefault();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int totalRecords = 0;
var employees = getDataService.GetAllEmployees().Select(x => new {
x.LastName
}).ToList();
if(!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
{
employees.OrderBy(x => sortColumn + " " + sortColumnDir);
}
totalRecords = employees.Count();
var data = employees.Skip(skip).Take(pageSize).ToList();
var result = Json(new
{ draw = draw,
recordsFiltered = totalRecords,
recordsTotal = totalRecords,
data = data
});
return result;
}
But if i put like following
var result = Json(new
{ draw = draw,
recordsFiltered = totalRecords,
recordsTotal = totalRecords,
data = data
},JsonRequestBehaviour.AllowGet);
then i can't find this thing in mvc core. Please help me what should i do.

In asp.net core, the Json method does not have an overload which takes JsonRequestBehavior. So you may simply call the Json method with the data you want to pass.
var result = Json(new
{ draw = draw,
recordsFiltered = totalRecords,
recordsTotal = totalRecords,
data = data
});
return result;

Related

Records Not Displaying in jquery.datatables using server side pagination processing

i am trying to get jquery.datatables working using server side processing and pagination. I used the following example article as a guide because its close to the version VS2017 that i am using-
https://www.c-sharpcorner.com/article/filtering-jquery-data-table-server-side-using-mvc-and-entity-framework/
When I run the application i get the following error:
DataTables warning: table id=tblrtr - Requested unknown parameter 'Id' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
and an empty grid that shows 10 blank lines and the right page count.
I have debugged the code and it finds all the records and values, and indeed the finalresult variable does return the contents of the 10 rows- but they dont seem to make it to the datatable grid.
Here is the controller code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using RTMGMTTest.Models;
namespace RTMGMTTest.Controllers
{
public class ReportsToRecordsController : Controller
{
private readonly RTMGMTContext _context;
public ReportsToRecordsController(RTMGMTContext context)
{
_context = context;
}
// GET: ReportsToRecords
public async Task<IActionResult> Index()
{
//return View(await _context.ReportsToRecords.ToListAsync());
return View();
}
[HttpPost]
public JsonResult RTRList(DTParameters param)
{
int TotalCount = 0;
var filtered = this.GetRTRFiltered(param.Search.Value, param.SortOrder, param.Start, param.Length, out TotalCount);
var RTRList = filtered.Select(o => new ReportsToRecords()
{
Id = o.Id,
ReportingId = o.ReportingId,
Title = o.Title,
Name = o.Name,
ReportsToId = o.ReportsToId,
EmployeeId = o.EmployeeId
});
DTResult<ReportsToRecords> finalresult = new DTResult<ReportsToRecords>
{
draw = param.Draw,
data = RTRList.ToList(),
recordsFiltered = TotalCount,
recordsTotal = filtered.Count
};
return Json(finalresult);
}
and
//for server side processing
public List<ReportsToRecords> GetRTRFiltered(string search, string sortOrder, int start, int length, out int TotalCount)
{
var result = _context.ReportsToRecords.Where(p => (search == null
|| (p.ReportingId != null && p.ReportingId.ToLower().Contains(search.ToLower())
|| p.Title != null && p.Title.ToLower().Contains(search.ToLower())
|| p.Name != null && p.Name.ToLower().Contains(search.ToLower())
|| p.ReportsToId != null && p.ReportsToId.ToLower().Contains(search.ToLower())
|| p.EmployeeId!= null && p.EmployeeId.ToLower().Contains(search.ToLower())
))).ToList();
TotalCount = result.Count;
result = result.Skip(start).Take(length).ToList();
switch (sortOrder)
{
case "ReportingId":
result = result.OrderBy(a => a.ReportingId).ToList();
break;
case "Title":
result = result.OrderBy(a => a.Title).ToList();
break;
case "Name":
result = result.OrderBy(a => a.Name).ToList();
break;
case "ReportsToId":
result = result.OrderBy(a => a.ReportsToId).ToList();
break;
case "EmployeeId":
result = result.OrderBy(a => a.EmployeeId).ToList();
break;
default:
result = result.AsQueryable().ToList();
break;
}
return result.ToList();
}
The view page looks as follows:
#model IEnumerable<RTMGMTTest.Models.ReportsToRecords>
#{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
if ($.fn.DataTable.isDataTable('#tblrtr')) {
$('#tblrtr').dataTable().fnDestroy();
$('#tblrtr').dataTable().empty();
}
var complete = $('#tblrtr').DataTable(
{
"serverSide": true,
"destroy": true,
"processing": true,
"ajax":
{
url: "/ReportsToRecords/RTRList",
method: "POST"
},
"columns": [
{ "data": "Id"},
{ "data": "ReportingId" },
{ "data": "Title" },
{ "data": "Name" },
{ "data": "ReportsToId" },
{ "data": "EmployeeId" }
]
}
);
/// Following code is for filter input to apply filter only on Enter
var itm = $("#tblrtr_filter input")
itm.unbind();
itm.keyup(function (e) {
//enter or tab
if (e.keyCode == 13) {
complete.search(this.value).draw();
}
});
});
</script>
<table class="table" id="tblrtr">
<thead>
<tr>
<th>
Id
</th>
<th>
ReportingId
</th>
<th>
Title
</th>
<th>
Name
</th>
<th>
ReportsToId
</th>
<th>
EmployeeId
</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
Does anyone know what would cause the data returned from the controller to not display and cause the resulting message? Thanks.

sample of kendo combo for relation table with id and value

i'm using kendo ui in my asp.net mvc 4 with razor views and encounter problem with kendo combo when the list load from an action via ajax with sending parameters to the server like the sample here:HERE
becuase the table has more then 2,000 rows.
when i load the edit page, the combo load and filter the data as expected, but the value of this field is - [object object].
i did declare the .DataTextField("ProffName") + .DataValueField("ID")
My ClientsController:
public ActionResult Edit(int id = 0)
{
Clients clients = db.Clients.Find(id);
if (clients == null)
{
return HttpNotFound();
}
ViewData["MyAgency"] = new SelectList(db.Agency, "ID", "AgentName", clients.AgencyId);
ViewData["MyCategory1"] = new SelectList(db.CategoryTbl, "ID", "category", clients.CategoryId);
List<SelectListItem> obj = new List<SelectListItem>();
obj.Add(new SelectListItem { Text = "male", Value = "1" });
obj.Add(new SelectListItem { Text = "female", Value = "2" });
obj.Add(new SelectListItem { Text = "choose", Value = "0" });
ViewData["MyMin"] = obj;
ViewBag.ProffID = new SelectList(db.ProfTBL, "ID", "ProffName", clients.ProffID);
ViewBag.Metapel = new SelectList(db.Workers, "ID", "WorkerName", clients.Metapel);
return View(clients);
}
My ProffController:
public ActionResult ProffVM_Read(string text)
{
var Proff_Tbl = db.ProfTBL.Select(proff => new ProffVm { ID = proff.ID, ProffName = proff.ProffName });
if (!string.IsNullOrEmpty(text))
{
Proff_Tbl = Proff_Tbl.Where(p => p.ProffName.Contains(text));
}
return Json(Proff_Tbl, JsonRequestBehavior.AllowGet);
}
and the Kendo combo:
#Html.Label("Proff")
#(Html.Kendo().ComboBoxFor(model => model.ProffID)
.Name("proffCbo")
.DataTextField("ProffName")
.DataValueField("ID")
.Events(e => e
.Select("proffCbo_select")
.Change("proffCbo_change")
)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("ProffVM_Read", "Proff")
.Data("onAdditionalData");
});
})
)
where am i wrong ???
i can change this combo to textbox but... i have to realize the magic.
Thanks
Change these two lines
var Proff_Tbl = db.ProfTBL.Select(proff => new ProffVm { ID = proff.ID, ProffName = proff.ProffName });
Proff_Tbl = Proff_Tbl.Where(p => p.ProffName.Contains(text));
to
var Proff_Tbl = db.ProfTBL.Select(proff => new ProffVm { ID = proff.ID, ProffName = proff.ProffName }).ToList();
Proff_Tbl = Proff_Tbl.Where(p => p.ProffName.Contains(text)).ToList();

Titanium: ListView load remote images

I've got the below bit of code which pull back a list of the users facebook contacts along with their profile picture, however the images are not loading for each user, it is only showing the images for a few users.
fb.requestWithGraphPath('me/friends', {
fields : 'first_name,last_name,id,installed,picture.width(120).height(120),gender'
}, 'GET', function(e) {
if (e.success) {
var d = JSON.parse(e.result);
var pData = [];
var iData = [];
var row = d.data;
row = row.sort(sortByName)
for (var i = 0; i < d.data.length; i++) {
var img = row[i].picture.data.url
if (row[i].installed) {
pData.push({
properties : {
title : row[i].first_name + " " + row[i].last_name,
id : row[i].id,
image : img,
gender : row[i].gender,
accessoryType : Ti.UI.LIST_ACCESSORY_TYPE_DISCLOSURE
},
template : Ti.UI.LIST_ITEM_TEMPLATE_DEFAULT
});
} else {
iData.push({
properties : {
title : row[i].first_name + " " + row[i].last_name,
id : row[i].id,
image : img,
accessoryType : Ti.UI.LIST_ACCESSORY_TYPE_DISCLOSURE
},
template : Ti.UI.LIST_ITEM_TEMPLATE_DEFAULT
});
}
}
var play = Ti.UI.createListSection({
headerTitle : 'Play with Facebook Friends',
items : pData
});
var invite = Ti.UI.createListSection({
headerTitle : 'Invite Facebook Friends',
items : iData
});
var listView = Ti.UI.createListView({
sections : [play, invite],
});
self.add(listView)
} else {
alert("Facebook Error");
}
})
The images are stored in var img = row[i].picture.data.url and pushed into the data array as part of image : img but not all images are loading.
Is there a way to force the images to load? and show a default image whilst they are loading?
Here is a link to complete example to do exactly what you are trying to accomplish abaove
http://www.clearlyinnovative.com/blog/post/34758524584/alloy-listview-facebook-friends#.UgexZGRATrg

jqGrid ASP.NET MVC4 initial sort

I'm using jqGrid as TreeGrid with ASP.NET MVC4 and have one problem:
My Model:
OrdersGrid = new JQGrid
{
Columns = new List<JQGridColumn>()
{
new JQGridColumn
{
DataField = "MeasureId",
// always set PrimaryKey for Add,Edit,Delete operations
// if not set, the first column will be assumed as primary key
PrimaryKey = true,
Visible = false,
Sortable = false
},
new JQGridColumn
{
DataField = "Name",
Width = 100,
Sortable = true
},
new JQGridColumn
{
DataField = "Symbol",
Width = 100
},
},
Width = Unit.Pixel(640),
Height = Unit.Percentage(100),
TreeGridSettings = new TreeGridSettings
{
Enabled = true
},
SortSettings = new SortSettings
{
AutoSortByPrimaryKey = false,
InitialSortColumn = "Name",
InitialSortDirection = SortDirection.Asc
}
};
My Controller:
public JsonResult DataRequested()
{
// Get both the grid Model and the data Model
// The data model in our case is an autogenerated linq2sql database based on Northwind.
var gridModel = new NavigatorModel();
...
var hierarchyRows = from measure in measures
select new
{
MeasureId = measure.MeasureId,
Name = measure.Name,
Symbol = measure.Symbol,
//ParentID = measure.ParentMeasureId != null ? measure.ParentMeasureId.ToString() : "",
tree_loaded = true,
tree_parent = measure.ParentMeasureId,
tree_level =LoadAllRowsExpanded_GetRowLevel(measure.ParentMeasureId, measures),
tree_leaf = LoadAllRowsExpanded_IsLeafRow(measure.MeasureId, measures),
tree_expanded = true
};
//var dataModel = new
// return the result of the DataBind method, passing the datasource as a parameter
// jqGrid for ASP.NET MVC automatically takes care of paging, sorting, filtering/searching, etc
return gridModel.OrdersGrid.DataBind(hierarchyRows.AsQueryable());
}
As above you can see that I'm setting the AutoSortByPrimaryKey set to false, but when the page is loaded, grid looks like that:
When I click on one of columns (Name or Symbol) to sort everything becomes fine - the Measure which is wrongly displayed goes under it's parent.
I have tried also with event to sort after "gridInitialize" but also no success.
Any ideas?

Dijit validator question within dynamically created validationbox , please help

I'm now trying to do a dynamically created table line , with dijit button, validation box.
The button id and textbox id is generate by index number, so how can my Validation box validator can know which line of validationbox is calling the validator?
Should I make the validator : testcall , being validator : function () {testcall(this.id)}, ????
function createNewRow() {
var tablebodyname = "RPDetailbody" ;
var mytablebody = document.getElementById(tablebodyname);
var thetabletr = document.createElement('tr');
var thetabletd1 = document.createElement('td');
var thetabletd2 = document.createElement('td');
var thetabletd3 = document.createElement('td');
var thisButton = new dijit.form.Button({
label : thelineindex ,
id : "I_del_butt"+thelineindex,
name : "I_del_butt"+thelineindex,
onClick : function() {
document.getElementById(tablebodyname).removeChild(thetabletr);
}
}).placeAt( thetabletd1 ) ;
var thisNumberTextBox = new dijit.form.NumberTextBox({
id : "I_seq_no"+thelineindex ,
name : "I_seq_no"+thelineindex ,
value : thelineindex+1 ,
required : "true",
maxLength : 2,
size : 2 ,
style : "width: 2em;",
missingMessage : "Every line must have sequence number"}).placeAt(thetabletd2) ;
var thisValidationTextBox1 = new dijit.form.ValidationTextBox({
id : "I_pig_code"+thelineindex ,
name : "I_pig_code"+thelineindex ,
type : "text" ,
required : "true",
maxLength : 3,
size : 3,
style : "width: 5em;",
validator : testcall ,
missingMessage : "Must have pigment code" }).placeAt(thetabletd3) ;
thetabletr.appendChild(thetabletd1);
thetabletr.appendChild(thetabletd2);
thetabletr.appendChild(thetabletd3);
mytablebody.appendChild(thetabletr);
thelineindex ++ ;
}
<tbody id="RPDetailbody">
<td><div id="delplace"></div></td>
<td><div id="seqplace"></div></td>
<td><div id="pigcodeplace"></div></td>
</tr>
</tbody>
However I've try to make it as javascript function call to my validator , but I found in the form submittion , using form.isValid() to verify all information can pass validation, it always returns fail !
Here are my validator :
function testcall ( thebtnID ) {
var strlen = thebtnID.length ;
var resultAreaID = "I_pigment_name"+ thebtnID.substring(10, strlen) ;
var pigcode = dijit.byId(thebtnID );
var bNoNameFound = ( "Error" == pigcode.get( "state" ) ) ? false:true;
var query = "thePig=" + encodeURI(pigcode.value );
if( "" == pigcode.value ) {
// for some required=true is not kicking in, so we are forcing it.
bNoNameFound = false;
pigcode._setStateClass();
} else {
if( false == pigcode._focused ) {
console.log( "Checking Pigment..." );
dojo.xhrPost({
url: 'ValidatePigmentInput.php',
handleAs: 'text',
postData: query ,
load: function( responseText ) {
if ( responseText == "no record!" ) {
// setting the state to error since the pigment is already taken
bNoNameFound = false;
pigcode.set( "state", "Error" );
//pigcode.displayMessage( "The Pigment dosen't exist..." );
document.getElementById(resultAreaID).innerHTML = "The Pigment dosen't exist...";
// used to change the style of the control to represent a error
pigcode._setStateClass();
} else {
if ( responseText == "pigment BANNED!" ) {
bNoNameFound = false;
pigcode.set( "state", "Error" );
document.getElementById(resultAreaID).innerHTML = "Pigment BANNED! Please don't use it!";
pigcode._setStateClass();
} else {
bNoNameFound = true;
pigcode.set( "state", "" );
document.getElementById(resultAreaID).innerHTML = responseText;
pigcode._setStateClass();
}
}
},
error: function(responseText) {
document.getElementById(resultAreaID).innerHTML = "Error";
}
});
}
}
return bNoNameFound;
}
You can do:
var thisValidationTextBox1 = new dijit.form.ValidationTextBox({
id: "I_pig_code" + thelineindex,
name: "I_pig_code" + thelineindex,
type: "text",
required: "true",
maxLength: 3,
size: 3,
style: "width: 5em;",
missingMessage: "Must have pigment code"
}).placeAt(thetabletd3);
thisValidationTextBox1.validator = function() {
return testcall(thisValidationTextBox1.id);
};
Ie. you need to pass the id to your testcall() function, but also you need to explicitly override the validator property of the widget.
See this in the Dojo reference guide.