i'm using datatable plugin in asp.net mvc project , while binding data it render wrong datetime value
the actual datetime value in database is 05-May-19 2:43:33 PM , in running the displayed value is /Date(1557060213477)/
the expected result it display datetime value that exist in database
here is my model
public int Id { get; set; }
[Required]
public string Name { get; set; }
Display(Name ="Upload File")]
public string FileUrl { get; set; }
public DateTime AddedOn { get; set; }
here is my view
<table id="DDR" class="table table-striped table-bordered dt-responsive nowrap">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Uploaded File</th>
<th>Uploaded At</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
</table>
#section scripts {
<link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script>
$(document).ready(function () {
debugger;
$("#DDR").DataTable({
"ajax": {
"url": "/DomesticDocRepositories/GetData",
"type": "GET",
"datatype": "json"
},
"columns": [
{
"data": "Id",
render: function (data, type) {
return ''+data+"";
}
},
{ "data": "Name" },
{
data: "FileUrl",
render: function (data, type) {
return "<a href='/DomesticFiles/" + data + " 'target='_blank''>" + data + "</a>";
}
},
{
"data": "AddedOn",
render: function (data, type) {
return '<span "title='+ data +"'>" + data +"</span>";
}
},
{
"render": function (data, type, full, meta) { return '<a class="btn btn-info" href="/DomesticDocRepositories/Edit/' + full.Id + '">Edit</a>'; }
},
{
data: null, render: function (data, type, row) {
return '<a class="btn btn-danger" href="/DomesticDocRepositories/Delete/' + row.Id + '">Delete</a>';
}
},
]
});
});
</script>
}
use moment.js for datetimes (docs).in your render, you should use in render:
{
render: function (data, type, row) {//data
return moment(row.AddedOn ).format('DD/MM/YYYY hh:mm:ss');//or another format you wantt.
}
}
Related
I have a panel where I take data from a view in database, and show them. The data are being showed but it is being replicated 3 times, I mean, each row apears 3 times in my table (panel).
When I use my filters, the data apears only one time though, as it should be.
I thought that I was calling my function "criarDataTables()" 3 times, but this is not the case.
This is in my Index.cshtml:
#section Scripts{
#Scripts.Render("~/bundles/typeahead")
#Scripts.Render("~/bundles/datatables")
#Scripts.Render("~/Scripts/js/bootstrap-datapicker.js")
#Scripts.Render("~/Scripts/js/bootstrap-datepicker.pt-BR.js")
#Scripts.Render("~/Scripts/jQuery-Mask/jquery.mask.min.js")
<script type="text/javascript">
var tbPainelTriagem;
var reload = false;
function criarDataTables() {
tbPainelTriagem = $("#tb-triagem").DataTable({
searching: false,
processing: true,
serverSide: true,
ajax: {
url: "/PainelTriagem/ListaPainelTriagem",
type: "POST",
data: {
customSearch: {
[...]
}
}
},
columns: [
{ data: "ID_VIEW" },
{ data: "TIPO" },
[...]
],
columnDefs: [
],
drawCallback: function (settings, json) {
$("#frm-filtro :input").prop("disabled", false);
}
});
}
$(document).ready(function () {
var listaDs;
$('#dsUnidIntField').attr("autocomplete", "off");
$('#dsUnidIntField').typeahead({
name: 'resultDs',
limit: 200,
minLength: 0,
source: function (query, process) {
itens = [];
listaDs = {};
$.post('/PainelTriagem/DsAutocomplete', { query: query }, function (data) {
$.each(data, function (i, item) {
listaDs[item.Nome] = item;
itens.push(item.Nome);
});
process(itens);
});
},
updater: function (item) {
var ds = listaDs[item];
$('#ID_VIEW', '#frm-filtro').val(ds);
return ds.Nome;
}
});
criarDataTables();
})
</script>
}
[...]
<table id="tb-triagem" class="table table-striped table-bordered dataTableLayout">
<thead>
<tr>
<th>ID View</th>
<th>Tipo</th>
[...]
</tr>
</thead>
</table>
This is in my PainelTriagemController.cs
using [...]
namespace PainelMV.Controllers
{
public class PainelTriagemController : Controller
{
[...]
[HttpPost]
public ActionResult ListaPainelTriagem(HCDataTableRequest<PainelTriagem> dataTableRequest)
{
try
{
HCDataTableResponse<PainelTriagemViewModel> dataTable = MyPainelTriagemManager
.ToList(dataTableRequest).CastViewModel(x => new PainelTriagemViewModel
{
ID_VIEW = x.ID_VIEW,
TIPO = x.TIPO == null ? " - " : x.TIPO.ToString(),
[...]
});
return Json(dataTable);
}
catch(Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
}
}
And this is in my PainelTriagemStore.cs
using [...]
namespace PainelMV.Data.Store
{
public class PainelTriagemStore : BaseStore<PainelTriagem, AppContext>
{
public PainelTriagemStore(AppContext context): base(context) { }
public HCDataTableResponse<PainelTriagem> ToList(HCDataTableRequest<PainelTriagem> dataTableRequest)
{
try
{
HCDataTableResponse<PainelTriagem> response = new HCDataTableResponse<PainelTriagem>();
var qr = _context.PainelTriagem.AsQueryable();
response.recordsTotal = qr.Count();
int? tipo = dataTableRequest.GetCustomSearchInt("tipo");
string nmPaciente = dataTableRequest.GetCustomSearchString("nmPaciente");
[...]
if (tipo != null)
{
qr = qr.Where(x => x.TIPO == tipo);
}
[...]
response.recordsFiltered = qr.Count();
qr = qr.OrderAndPaging(dataTableRequest);
response.data = qr.ToList();
return response;
}
catch(Exception ex)
{
throw ex;
}
}
}
}
I want to show my data in datatable but I get the above error.
My Table Property:
[Table("DimStatus", Schema = "dmg")]
public class PolicyState
{
[Key]
public int Code { get; set; }
public string Title { get; set; }
}
My Api :
[Route("api/[controller]/[action]")]
[ApiController]
public class ReportController : Controller
{
private ICommonServices _CommonService;
public ReportController(ICommonServices CommonService)
{
_CommonService = CommonService;
}
// GET
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult GetPolicyState()
{
try
{
var draw = Request.Form["draw"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault();
var length = Request.Form["length"].FirstOrDefault();
var sortColumn = Request.Form["columns[" + Request.Form["order[0]
[column]"].FirstOrDefault() +
"][name]"].FirstOrDefault();
var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault();
var searchValue = Request.Form["search[value]"].FirstOrDefault();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
var PolicyData = (from tempcustomer in _CommonService.GetPolicyState() select tempcustomer);
//var PolicyData = _CommonService.GetPolicyState();
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDirection)))
{
PolicyData = PolicyData.OrderBy(sortColumn + " " + sortColumnDirection);
}
if (!string.IsNullOrEmpty(searchValue))
{
PolicyData = PolicyData.Where(m => m.Title.Contains(searchValue));
}
recordsTotal = PolicyData.Count();
var data = PolicyData.Skip(skip).Take(pageSize).ToList();
var jsonData = new
{
draw = draw,
recordsFiltered = recordsTotal,
recordsTotal = recordsTotal,
data = data
};
var testd = jsonData;
return Ok(jsonData);
}
catch (Exception ex)
{
throw;
}
}
}
and last my index.cshtml:
<link rel="stylesheet" type="text/css"
href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.css">
<div class="container">
<br />
<div style="width:90%; margin:0 auto;">
<table id="DimStatus" class="table table-striped table-bordered dt-responsive nowrap"
width="100%" cellspacing="0">
<thead>
<tr>
<th>Code</th>
<th>Title</th>
<th>asdf</th>
</tr>
</thead>
</table>
</div>
</div>
#section Scripts
{
<script type="text/javascript" charset="utf8"
src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function () {
dataTable = $('#DimStatus').dataTable({
serverSide: true,
processing: true,
//searchDelay: 500,
pageLength: 10,
infoFiltered: true,
orderMulti: false,
"ajax": {
"url": "/api/Report/GetPolicyState",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "Code", "name": "Code", "autoWidth": true },
{ "data": "Title", "name": "Title", "autoWidth": true },
{
"render": function (data, row) {
return "<a href='#' class='btn btn-danger' onclick=DeleteCustomer('" +
row.Code + "'); >Details</a>";
}
},
]
});
});
would if anybody know the issue help me solve it. thank you in advanced.
Your error clearly states that your returning data does not have any property name "Code". Make sure that the data structure your are returning contains property name "Code" as you are processing on PolicyData class and not PolicyState class that you have showed in the sample code.
I am using JQuery DataTables and AJAX. I am having difficulty getting fields from the secondary table that are connected through the primary key. The only thing that I am able to show is the primary key. In this case concern_id.
Model: Question
public int question_id { get; set; }
public int concern_id { get; set; }
public string question_text { get; set; }
public string question_answer { get; set; }
Model: Concern
public int concern_id { get; set; }
public string concern_desc { get; set; }
I would like to be able to show the concern_desc. If I don't use AJAX in datatables I can easily grab the field I need.
Example:
#Html.DisplayNameFor(model => model.concern.concern_desc)
Controller:
public JsonResult GetQuestionRecord()
{
bool proxyCreation = db.Configuration.ProxyCreationEnabled;
try
{
db.Configuration.ProxyCreationEnabled = false;
var list = (from q in db.questions
join c in db.concerns on q.concern_id equals c.concern_id
select q).ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(ex.Message);
}
finally
{
db.Configuration.ProxyCreationEnabled = proxyCreation;
}
}
View:
<table id="DataTable" class="display" style="width:100%">
<thead>
<tr>
<th>ConcernID</th>
<th>QuestionText</th>
</tr>
</thead>
<tbody></tbody>
The JavaScript:
$(document).ready(function () {
GetQuestionRecord();
});
var GetQuestionRecord = function () {
$.ajax({
type: "Get",
url: '#Url.Action("GetQuestionRecord","questions")',
success: function (response) {
BindDataTable(response);
}
});
}
var BindDataTable = function (response) {
$("#DataTable").DataTable({
"aaData": response,
"aoColumns": [
{ "mData": "concern_id" },
{ "mData": "question_text" },
]
});
}
What do I change in the "mData : concern_id" to in order to display "concern_desc" . I tried:
{ "mData": "concern_desc" }
And
{ "mData": "concern.concern_desc" }
Step 1: Change your LINQ query in the Controller to this.
var list = (from q in db.questions
join c in db.concerns on q.concern_id equals c.concern_id
select new
{
question_id = q.question_id,
concern_id = q.concern_id,
question_text = q.question_text,
question_answer = q.question_aswer,
concern_desc = c.concern_desc
}).ToList();
Step 2: Change your BindDataTable JS code to.
var BindDataTable = function (response) {
$("#DataTable").DataTable({
"aaData": response,
"aoColumns": [
{ "mData": "concern_id" },
{ "mData": "question_text" },
{ "mData": "concern_desc" }
]
});
I am filling my jQuery Datatable (ver: 1.10.15) from WebAPI and it works but when I search in datatable via searchbox then it doesn't fill the datatable with updated data. Why?
I checked, it sends search value and brings the updated data from server but doesn't populate the table with newly returned data.
function show()
{
$('#example').DataTable({
// "processing": true,
"serverSide": true,
"retrieve": true,
"destroy": true,
"pagination": true,
// "contentType": 'application/json; charset=utf-8',
"ajax": "http://localhost:28071/Users"
});
}
UPDATE:
C# api code:
namespace WebApiHimHer.Controllers
{
public class UsersController : ApiController
{
[HttpGet]
public DTResult GetData([FromUri]DTParameters v)
{
List<string[]> s = new List<string[]>();
//List<basicoperations> s = new List<basicoperations>();
basicoperations bo= new basicoperations();
s = bo.getUsers(v.length, v.start, 1, v.sortOrder, v.search.Value);
DTResult r = new DTResult();
r.draw = 1;
r.recordsFiltered = s.Count;
r.recordsTotal = 100; ;
r.data = s;
return r;
}
}
public class DTResult
{
public int draw { get; set; }
public int recordsTotal { get; set; }
public int recordsFiltered { get; set; }
public List<string[]> data { get; set; }
}
public abstract class DTRow
{
public virtual string DT_RowId
{
get { return null; }
}
public virtual string DT_RowClass
{
get { return null; }
}
public virtual object DT_RowData
{
get { return null; }
}
}
public class DTParameters
{
public int draw { get; set; }
public DTColumn[] columns { get; set; }
public DTOrder[] order { get; set; }
public int start { get; set; }
public int length { get; set; }
public DTSearch search { get; set; }
public string sortOrder
{
get
{
return columns != null && order != null && order.Length > 0
? (columns[order[0].Column].Data + (order[0].Dir == DTOrderDir.DESC ? " " + order[0].Dir : string.Empty))
: null;
}
}
}
public class DTColumn
{
public string Data { get; set; }
public string Name { get; set; }
public bool Searchable { get; set; }
public bool Orderable { get; set; }
public DTSearch Search { get; set; }
}
public class DTOrder
{
public int Column { get; set; }
public DTOrderDir Dir { get; set; }
}
public enum DTOrderDir
{
ASC,
DESC
}
public class DTSearch
{
public string Value { get; set; }
public bool Regex { get; set; }
}
}
I am posting a Request and response after initial table load and after performing a search
After initial load:
Request:
_
1503560388132
columns[0][data]
0
columns[0][name]
columns[0][orderable]
true
columns[0][search][regex]
false
columns[0][search][value]
columns[0][searchable]
true
columns[1][data]
1
columns[1][name]
columns[1][orderable]
true
columns[1][search][regex]
false
columns[1][search][value]
columns[1][searchable]
true
draw
2
length
10
order[0][column]
0
order[0][dir]
asc
search[regex]
false
search[value]
2
start
0
Response:
{"draw":1,"recordsTotal":4,"recordsFiltered":25,"data":[["Hunain","123"],["hk","asd"],["daenerys Targaryen"
,"123"],["",""]]}
After performing a search:
Request:
_
1503560409319
columns[0][data]
0
columns[0][name]
columns[0][orderable]
true
columns[0][search][regex]
false
columns[0][search][value]
columns[0][searchable]
true
columns[1][data]
1
columns[1][name]
columns[1][orderable]
true
columns[1][search][regex]
false
columns[1][search][value]
columns[1][searchable]
true
draw
2
length
10
order[0][column]
0
order[0][dir]
asc
search[regex]
false
search[value]
w
start
0
Response:
{"draw":1,"recordsTotal":1,"recordsFiltered":25,"data":[["Waleed","123"]]}
The reason was that draw parameter being sent and received was not same because I took draw static in the server code so mismatched. I returned the same draw parameter as it was sent.
From the docs :
The draw counter that this object is a response to - from the draw
parameter sent as part of the data request. Note that it is strongly
recommended for security reasons that you cast this parameter to an
integer, rather than simply echoing back to the client what it sent in
the draw parameter, in order to prevent Cross Site Scripting (XSS)
attacks.
Edit
function show(){
$("#example").DataTable({
serverSide: true,
processing: true,
columns : [
{ data : 'FirstName' },
{ data : 'LastName' }
],
ajax: {
url: "https://api.myjson.com/bins/384sr",
dataSrc : ''
}
});
}
show();
Html
<table id="example" class="display">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
Jsfiddle
Not sure if you found your error, but check this out.
Verify the configuration/system.webServer/security/requestFiltering/requestLimits#maxQueryString setting in the applicationhost.config or web.config file.
//For me it was two things.
//wrap the table javascript with
//function _displayItems(data) { var table = $('#...
//Then using the closing brackets:
//destroy then clear
productsTable.destroy();
productsTable.clear();
}
function _displayItems() {
fetch(uri)
.then(response => response.json())
.then(data => _displayItems(data))
.catch(error => console.error('Unable to get items.', error));
}
var tableName = $('#data').DataTable({
"processing": true,
"data": data,
"columns": [
{ "name": "name", "data": "name" },
{ "name": "id", "data": "id" },
{
"render": function (data, type, full, meta) {
var buttonID = "edit_" + full.id;
return '<a id="' + buttonID + '" class="btn btn-outline-info waves-effect editBtn" role="button">Edit</a>';
}
},
{
"render": function (data, type, full, meta) {
var buttonID = "delete_" + full.id;
return ' <a id="' + buttonID + '" onclick="deleteUserRoleModal()" type="button" class="btn btn-outline-danger waves-effect removeRole" role="button">Delete</a>';
}
}
],
"responsive": true,
"dom": 'Bfrtip',
"buttons": [
'copy', 'excel', 'pdf',
{
text: 'Delete',
}
],
"initComplete": function () {
this.api().columns([0]).every(function () {
var column = this;
var select = $('<select class="selectpicker" data-size="5" data-live-search="true"><option value="">Application Role (All)</option></select>')
.appendTo("#table").end()
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.cells('', column[0]).render('display').sort().unique().each(function (d, j) {
if (column.search() === '^' + d + '$') {
select.append('<option value="' + d + '" selected="selected">' + d + '</option>')
}
else {
select.append('<option value="' + d + '">' + d + '</option>')
}
});
});
},
"bJqueryUI": true,
"bPaginate": false,
"aaSorting": [[1, 'asc']],
"aoPreSearchCols": [[1]],
"lengthMenu": [
[12, 24, 48, 1000],
['12', '24', '48', 'all']
],
"language": {
searchPlaceholder: "🔎 Role Screen ",
search: " ",
}
});
$.fn.dataTable.Buttons(productsTable, {
buttons: [
'copy', 'excel', 'pdf'
]
});
productsTable.buttons().container()
.appendTo($('.col-sm-6:eq(0)', productsTable.table().container()));
$("#todos" + "#table").DataTable({
responsive: true
});
//destroy then clear
productsTable.destroy();
productsTable.clear();
}
I would like to know how to convert the following object to C# when reaching the mathod. I needed to create an object which can hold multiple array's within JSON something like the following
{
"cars": {
"Ferrari":["LaFerrari","F40","458"],
"Porsche":["911","959"],
"Lamborghini":["Aventador"]
}
}
The code I used is the following within cshtml
<div class="row">
<div class="col-md-4">
<div>
<input type="text" id="txtKey" />
<input type="button" id="btnKey" />
</div>
<div>
<input type="text" id="txtChild" />
<input type="button" id="btnChild" />
</div>
<div>
<input type="button" id="btnSubmit" />
</div>
</div>
</div>
#section scripts
{
$(function () {
AddKeyToDictionary('Ferrari');
AddKeyToDictionary('Porsche');
AddKeyToDictionary('Lamborghini');
AddValueToDictionary('Ferrari', 'LaFerrari');
AddValueToDictionary('Ferrari', 'F40');
AddValueToDictionary('Ferrari', '458');
AddValueToDictionary('Porsche', '911');
AddValueToDictionary('Porsche', '959');
AddValueToDictionary('Lamborghini', 'Aventador');
$('#btnKey').click(function () {
AddKeyToDictionary($('#txtKey').val());
});
$('#btnChild').click(function () {
AddValueToDictionary($('#txtKey').val(), $('#txtChild').val());
});
$('#btnSubmit').click(function () {
submit();
});
});
var dict = {};
function AddKeyToDictionary(key) {
dict[key] = [];
}
function AddValueToDictionary(key, value) {
dict[key].push(value);
}
function submit() {
var url = "#Url.Action("UpdateCustomFields", "Home")";
var data = JSON.stringify({ 'cars': dict });
$.ajax({
type: "POST",
contentType: "Application/json;charset=utf-8",
url: url,
data: data,
datatype: "json",
success: function (msg) {
},
error: function (request, status, error) {
displayDialog("A communication Error has occurred, please contact IT support: " + error);
}
});
}
</script>
}
I've tried the following within MVC (got this from a JSON c# convertor)
public JsonResult UpdateCustomFields(RootObject cars)
{
return Json("");
}
}
public class Cars
{
public List<string> Ferrari { get; set; }
public List<string> Porsche { get; set; }
public List<string> Lamborghini { get; set; }
}
public class RootObject
{
public Cars cars { get; set; }
}
The car makes should be dynamic and then the arrays below should be converted correctly.
I also tried to iterate through the array and changed them all to key value pairs which still wasn't rendering
function convertToKeyValue() {
submitValue = [];
for (var k in dict) {
if (dict.hasOwnProperty(k)) {
if (dict[k].length > 0) {
for (var i = 0; i < dict[k].length; i++) {
submitValue.push({ key: k, value: dict[k][i] });
}
} else {
submitValue.push({ key: k, value: '' });
}
}
}
}
Passing them through the name/value pairs I was able to see them in the dynamic property within the controller but can't get to the variables.
public JsonResult UpdateClientCustomFields(object cars)
{
var result = customFields.XmlSerializeToString();
return Json("hello");
}
If anyone can help or point me in the right direction.
Thanks
Updated: I've had to convert the javascript array to a list of key pairs (not ideal) and use List> cars as the paramter, the model is not ideal, but will use this until I find a better way.
Here is the updated code
HTML
<input type="button" id="btnSubmit2" />
var submitValue = [];
function convertToKeyValue() {
submitValue = [];
for (var k in dict) {
if (dict.hasOwnProperty(k)) {
//alert("Key is " + k + ", value is" + dict[k]);
//alert("KEY: " + k);
if (dict[k].length > 0) {
for (var i = 0; i < dict[k].length; i++) {
//alert("childrec: " + dict[k][i]);
submitValue.push({ key: k, value: dict[k][i] });
}
} else {
submitValue.push({ key: k, value: '' });
}
}
}
}
function submit2() {
convertToKeyValue();
var url = "#Url.Action("UpdateCustomFields2", "Home")";
var data = JSON.stringify({ 'cars': submitValue });
$.ajax({
type: "POST",
contentType: "Application/json;charset=utf-8",
url: url,
data: data,
datatype: "json",
success: function (msg) {
},
error: function (request, status, error) {
}
});
}
MVC
public JsonResult UpdateCustomFields2(List<Dictionary<string, string>> cars)
{
return Json("");
}
Try changing your cars property in RootObject to public Dictionary<string,List<string>> cars {get; set;}
Try to make your input param as string and then deserialize it to your object.
public JsonResult UpdateCustomFields(string cars)
{
RootObject yourCars = JsonConvert.DeserializeObject<RootObject>(cars);
return Json("");
}
Good luck :)
Unless I am missing something, the following seems to work fine
public class Program
{
public void Main(string[] args)
{
var json = #"
{
""cars"": {
""Ferrari"":[""LaFerrari"",""F40"",""458""],
""Porsche"":[""911"",""959""],
""Lamborghini"":[""Aventador""]
}
}
";
var dataObj = JsonConvert.DeserializeObject<Data>(json);
}
public class Data
{
public Dictionary<string, List<string>> Cars { get; set; }
}
}
Which version of JSON.NET are you using? I remember older versions had issues with dictionaries, but you could probably just create your own converter if that is the case.