I'm getting the following error. I know there are similar answered questions but I have tried to use those answers but I am still unable to see my error.
Error Message:
I have the correct amount of columns in the table and in the request. I have checked for typo's. I am using a video as a guide and I have done everything exactly the same, yet mine doesn't work
code:
<table id="myTable">
<thead>
<tr>
<th>Title</th>
<th>FirstName</th>
<th>Surname</th>
<th>Address1</th>
<th>Address2</th>
<th>Town</th>
<th>Account1</th>
<th>Account2</th>
</tr>
</thead>
</table>
#section mydataTable{
<script type="text/javascript" charset="utf8"
src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function () {
$('#myTable').DataTable(
{
"processing": true,
"filter": false,
"serverSide": true,
"paging": false,
"responsive": true,
"ajax":
{
"url": "#Url.Action("LoadData")",
"datatype": "json",
"type": "POST",
},
"columnDefs": [
{ "defaultContent": "-", "targets": "_all" },
{ "width": "auto", "targets": 0, "orderable": false },
{ "width": "auto", "targets": 1, "orderable": false },
{ "width": "auto", "targets": 2, "orderable": false },
{ "width": "auto", "targets": 3, "orderable": false },
{ "width": "auto", "targets": 4, "orderable": false },
{ "width": "auto", "targets": 5, "orderable": false },
{ "width": "auto", "targets": 6, "orderable": false },
{ "width": "auto", "targets": 7, "orderable": false },
],
"columns": [
{ "data": "Title", "name": "CTitle" },
{ "data": "FirstName", "name": "CFirstName" },
{ "data": "Surname", "name": "CSurname" },
{ "data": "Address1", "name": "CAddress1" },
{ "data": "Address2", "name": "CAddress2" },
{ "data": "Town", "name": "CTown" },
{ "data": "Account1", "name": "CAccount1" },
{ "data": "Account2", "name": "CAccount2" },
],
});
});
</script>
}
C#:
public JsonResult LoadData()
{
IEnumerable<DeathClaims> deathclaims = GetDc();
return Json(new { data = deathclaims, recordsFiltered = deathclaims.Count(), recordsTotal = deathclaims.Count() });
}
private IEnumerable<DeathClaims> GetDc()
{
List<DeathClaims> deathlist = new List<DeathClaims>()
{
new DeathClaims {
Title = "Mr",
FirstName = "Michael",
Surname = "Smith",
Address1 = "132 Spalding Road",
Address2 = "TS252JP",
Town = "Hartlepool",
Account1 = "Current Account 1.0%",
Account2 = "Super Saver 3.0%"},
new DeathClaims {
Title = "Mr",
FirstName = "Steve",
Surname = "Smith",
Address1 = "1 Something Close",
Address2 = "TS273QQ",
Town = "Hartlepool",
Account1 = "Current Account 1.0%",
Account2 = "Super Saver 2.0%"}
};
return deathlist;
}
None of the data is getting through - I'm sure it's a small issue but I just cant see it
Thank you in advance for your help
Thanks
For DataTables plugin to work at server-side. You need to return the JSON in LoadData() method as follow i.e.
...
// Initialization.
string search = Request.Form.GetValues("search[value]")[0];
string draw = Request.Form.GetValues("draw")[0];
string order = Request.Form.GetValues("order[0][column]")[0];
string orderDir = Request.Form.GetValues("order[0][dir]")[0];
int startRec = Convert.ToInt32(Request.Form.GetValues("start")[0]);
int pageSize = Convert.ToInt32(Request.Form.GetValues("length")[0]);
...
// Process your code.
...
JsonResult result = this.Json(new { draw = Convert.ToInt32(draw), recordsTotal = totalRecords, recordsFiltered = recFilter, data = data }, JsonRequestBehavior.AllowGet);
return result;
...
The above properties of DataTables plugin are needed to be captured and maintained in your code by yourself.
Related
I get the following JSON file by accessing a REST API in C#
[{
"id": 71,
"parent_id": 0,
"name": "Espace priv\u00e9",
"can_read": true,
"can_download": true,
"can_write": true,
"can_edit": true,
"can_delete": true,
"can_share": true,
"creation": "2022-07-12T09:53:34+00:00",
"modification": "2022-07-12T09:53:34+00:00",
"owner": "Sylvain KRIER",
"owner_id": "23"
}, {
"id": 80,
"parent_id": 0,
"name": "CLI12",
"can_read": true,
"can_download": true,
"can_write": true,
"can_edit": true,
"can_delete": true,
"can_share": true,
"creation": "2022-07-13T07:43:25+00:00",
"modification": "2022-07-13T08:25:46+00:00",
"owner": "Patrimoine Click",
"owner_id": "2",
"flags": 2
}, {
"id": 53,
"parent_id": 0,
"name": "DOCUMENTATION",
"can_read": true,
"can_download": true,
"can_write": true,
"can_edit": true,
"can_delete": true,
"can_share": true,
"creation": "2022-06-30T14:38:55+00:00",
"modification": "2022-06-30T14:39:05+00:00",
"owner": "Patrimoine Click",
"owner_id": "2",
"flags": 2
}, {
"id": 77,
"parent_id": 0,
"name": "Mme AMSELLEM Smadar",
"can_read": true,
"can_download": true,
"can_write": true,
"can_edit": true,
"can_delete": true,
"can_share": true,
"creation": "2022-07-12T10:33:29+00:00",
"modification": "2022-07-12T10:33:42+00:00",
"owner": "Patrimoine Click",
"owner_id": "2",
"flags": 2
}, {
"id": 68,
"parent_id": 0,
"name": "Mr NGUIMFACK Guy",
"can_read": true,
"can_download": true,
"can_write": true,
"can_edit": true,
"can_delete": true,
"can_share": true,
"creation": "2022-07-12T08:41:33+00:00",
"modification": "2022-07-12T13:28:06+00:00",
"owner": "Patrimoine Click",
"owner_id": "2",
"flags": 2
}, {
"id": 83,
"parent_id": 0,
"name": "vergne-CLI1",
"can_read": true,
"can_download": true,
"can_write": true,
"can_edit": true,
"can_delete": true,
"can_share": true,
"creation": "2022-07-13T08:20:06+00:00",
"modification": "2022-07-13T08:23:29+00:00",
"owner": "Sylvain KRIER",
"owner_id": "23",
"flags": 2
}, {
"id": 110,
"parent_id": 0,
"name": "krier1",
"can_read": true,
"can_download": true,
"can_write": true,
"can_edit": true,
"can_delete": true,
"can_share": true,
"creation": "2022-07-21T08:57:35+00:00",
"modification": "2022-07-21T08:57:35+00:00",
"owner": "Sylvain KRIER",
"owner_id": "23",
"flags": 2
}
]
It's a folder list. I need to get the "id" of each folder with the "name"
I try to deserialize the JSON string like this, but it doesn't work :
var a = JObject.Parse(((RestSharp.RestResponseBase)resultat.Value).Content).SelectToken("id").ToList();
((RestSharp.RestResponseBase)resultat.Value).Content is the JSON string mentioned
Thanks for giving me help.
Personally, I always deserialize my JSON to a statically typed object before doing anything else with it, in this case you can just create a mostly empty JsonDirectory class with just the id property and deserialize to a list of it, like so
public class JsonDirectory
{
[JsonPropertyName("id")]
public int Id { get; set; }
}
// Deserialize
var json = "...";
var jsonDirectory = JsonSerializer.Deserialize<List<JsonDirectory>>(json);
foreach (var jd in jsonDirectory)
Console.WriteLine(jd.Id);
Here's a demo showcasing his working on your example JSON
P.S this answer uses System.Text.Json, if you're using Newtonsoft.Json then you'll need to change out [JsonPropertyName("id")] with [JsonProperty("id")] and the deserialization line to JsonConvert.DeserializeObject<List<JsonDirectory>>(json)
you can use linq to create a list
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
List<IdName> idNameList = JArray.Parse(json)
.Select(j => new IdName { Id = (int)j["id"], Name = (string)j["name"] }).ToList();
public class IdName
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public int Name { get; set; }
}
result
[
{
"Id": 71,
"Name": "Espace privé"
},
{
"Id": 80,
"Name": "CLI12"
},
{
"Id": 53,
"Name": "DOCUMENTATION"
},
{
"Id": 77,
"Name": "Mme AMSELLEM Smadar"
},
{
"Id": 68,
"Name": "Mr NGUIMFACK Guy"
},
{
"Id": 83,
"Name": "vergne-CLI1"
},
{
"Id": 110,
"Name": "krier1"
}
]
I am trying to get all Epics from ADO using the below code
string PAT = "sdsd";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", PAT))));
string query = "SELECT [System.Id], [System.WorkItemType], [System.Title], [System.State], [System.AreaPath], [System.IterationPath], [System.TeamProject], [System.WorkItemType] FROM workitems WHERE System.WorkItemType='Epic' ORDER BY [System.ChangedDate] DESC ";
var q = JsonConvert.SerializeObject(new WiqlQuery() { query = query });
using (HttpResponseMessage response =client.PostAsync("https://dev.azure.com/{Org}/_apis/wit/wiql?api-version=6.0",new StringContent(q,Encoding.UTF8,"application/json")).GetAwaiter().GetResult())
{
response.EnsureSuccessStatusCode();
string responseBody = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
string k = "";
}
}
Code executes without any trouble. But if I run the above query in ADO query editor, its returning all the columns in the Select statement.
But when I run the same in Code, I am not all getting any of those columns. Instead I am getting below JSON
{
"queryType": "flat",
"queryResultType": "workItem",
"asOf": "2021-07-02T08:30:15.84Z",
"columns": [
{
"referenceName": "System.Id",
"name": "ID",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.Id"
},
{
"referenceName": "System.WorkItemType",
"name": "Work Item Type",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.WorkItemType"
},
{
"referenceName": "System.Title",
"name": "Title",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.Title"
},
{
"referenceName": "System.State",
"name": "State",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.State"
},
{
"referenceName": "System.AreaPath",
"name": "Area Path",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.AreaPath"
},
{
"referenceName": "System.IterationPath",
"name": "Iteration Path",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.IterationPath"
},
{
"referenceName": "System.TeamProject",
"name": "Team Project",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.TeamProject"
},
{
"referenceName": "System.WorkItemType",
"name": "Work Item Type",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.WorkItemType"
}
],
"sortColumns": [
{
"field": {
"referenceName": "System.ChangedDate",
"name": "Changed Date",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.ChangedDate"
},
"descending": true
}
],
"workItems": [
{
"id": 61380,
"url": "https://dev.azure.com/{organization}/_apis/wit/workItems/613810"
},
{
"id": 61834
}
]
}
What could be the reason or how to get all the columns of data we have specified in Select statement
Yes, RUN WIQL returns only the list of ids. Then you can use Get Work Items Batch to get only needed fields:
POST https://dev.azure.com/fabrikam/_apis/wit/workitemsbatch?api-version=6.1-preview.1
BODY:
{
"ids": [
297,
299,
300
],
"fields": [
"System.Id",
"System.Title",
"System.WorkItemType",
"Microsoft.VSTS.Scheduling.RemainingWork"
]
}
Note: Im working with System.Text.Json package
Below is JSON I am getting from a database. I have to go through each of the keys in the JSON and check if there is a period (.) in the key name; if so, I need to add a property required with the value of true in the JSON in order to provide runtime validation:
validate:{"required", true}
Here is my JSON:
{
"display": "wizard",
"settings": {},
"components": [{
"title": "Event Information",
"label": "Event Information",
"type": "panel",
"key": "EventInformation",
"components": [{
"label": "Row1Columns",
"columns": [{
"components": [{
"label": "Event Date",
"format": "dd/MM/yyyy hh:mm a",
"tableView": false,
"datePicker": {
"disableWeekends": false,
"disableWeekdays": false
},
"validate": {
"unique": true
},
"key": "Event.EventDate",
"type": "datetime",
"input": true,
"suffix": "<i ref=\"icon\" class=\"fa fa-calendar\" style=\"\"></i>",
"widget": {
"type": "calendar",
"displayInTimezone": "viewer",
"language": "en",
"useLocaleSettings": false,
"allowInput": true,
"mode": "single",
"enableTime": true,
"noCalendar": false,
"format": "dd/MM/yyyy hh:mm a",
"hourIncrement": 1,
"minuteIncrement": 1,
"time_24hr": false,
"minDate": null,
"disableWeekends": false,
"disableWeekdays": false,
"maxDate": null
}
}],
"width": 6,
"offset": 0,
"push": 0,
"pull": 0
}, {
"components": [{
"label": "Duration (minutes)",
"mask": false,
"spellcheck": true,
"tableView": false,
"delimiter": false,
"requireDecimal": false,
"inputFormat": "plain",
"key": "Event.Duration",
"type": "number",
"input": true
}],
"width": 6,
"offset": 0,
"push": 0,
"pull": 0
}],
"tableView": false,
"key": "row1Columns",
"type": "columns",
"input": false
}, {
"label": "Row2Columns",
"columns": [{
"components": [{
"label": "Event Category",
"widget": "choicesjs",
"tableView": true,
"dataSrc": "custom",
"data": {
"custom": "values = getEventCategoryValues()"
},
"valueProperty": "AgencyEventCategoryId",
"template": "<span>{{ item.text }}</span>",
"selectThreshold": 0.3,
"validate": {
"required": true
},
"key": "Event.AgencyEventCategoryId",
"type": "select",
"indexeddb": {
"filter": {}
},
"input": true
}],
"width": 6,
"offset": 0,
"push": 0,
"pull": 0
}, {
"components": [{
"label": "Attendance",
"widget": "choicesjs",
"tableView": true,
"multiple": false,
"dataSrc": "custom",
"data": {
"custom": "values = getAttendanceValues()"
},
"valueProperty": "AgencyEventAttendanceId",
"template": "<span>{{ item.text }}</span>",
"selectThreshold": 0.3,
"validate": {
"required": true,
},
"key": "Event.AgencyEventAttendanceId",
"type": "select",
"indexeddb": {
"filter": {}
},
"input": true
}],
"width": 6,
"offset": 0,
"push": 0,
"pull": 0
}],
"tableView": false,
"key": "row2Columns",
"type": "columns",
"input": false
}, {
"label": "Event Options",
"widget": "choicesjs",
"tableView": true,
"multiple": true,
"dataSrc": "custom",
"data": {
"custom": "values = getEventManagerValues(data.Event.AgencyEventCategoryId)"
},
"template": "<span>{{ item.text }}</span>",
"refreshOn": "Event.AgencyEventCategoryId",
"clearOnRefresh": true,
"selectThreshold": 0.3,
"calculateServer": false,
"validate": {
"required": true,
"multiple": true
},
"key": "Event.EventDetail",
"type": "select",
"indexeddb": {
"filter": {}
},
"input": true
}, {
"label": "Casenote",
"wysiwyg": true,
"autoExpand": true,
"spellcheck": true,
"tableView": true,
"calculateServer": false,
"key": "Event.EventCasenote[0].Casenote",
"type": "textarea",
"input": true
}],
"input": false,
"tableView": false,
"breadcrumbClickable": true,
"buttonSettings": {
"previous": true,
"cancel": true,
"next": true
},
"collapsible": false
}]
}
One of the options would be to parse json into JObject and add property to it via Newtonsoft's Json.NET:
var obj = JObject.Parse("{'key':'value'}");
obj.Add("required", true);
Console.WriteLine(obj); // { "key": "value", "required": true }
To add new object you can use this overload of Add:
obj.Add("validate", JObject.FromObject(new { required = true }));
So the whole solution will look something like this:
var obj = JObect.Parse(your_json);
foreach(var token in obj.DescendantsAndSelf().ToList()) // ToList is important!!!
{
if(token is JObject xObj)
{
// check your conditions for adding property
// check if object does not have "validate" property
if(satisfies_all_conditions)
{
xObj.Add("validate", JObject.FromObject(new { required = true }));
}
}
}
I was having similar issue, and have found a solution, see below the code and comments. I am using Newtonsoft though but it is worth checking if you can use Newtonsoft library and have not found a solution for System.Text.Json.
All controls in your JSON are part of component object/array so we can use JSONPath, see the link for more details.
public void IterateJson(JObject obj, string mandatoryFieldKey)
{
JToken jTokenFoundForMandatoryField = obj.SelectToken
("$..components[?(#.key == '" + mandatoryFieldKey + "')]");
//Now we convert this oken into an object so that we can add properties/objects in it
if (jTokenFoundForMandatoryField is JObject jObjectForMandatoryField)
{
//We check if validate already exists for this field, if it does not
//exists then we add validate and required property inside the if condition
if (jObjectForMandatoryField["validate"] == null)
jObjectForMandatoryField.Add("validate",
JObject.FromObject(new { required = true })); //add validate and required property
else
{
//If validate does not exists then code comes here and
//we convert the validate into a JObject using is JObject statement
if (jObjectForMandatoryField["validate"] is JObject validateObject)
{
//We need to check if required property already exists,
//if it does not exists then we add it inside the if condition.
if (validateObject["required"] == null)
{
validateObject.Add("required", true); //add required property
}
}
}
}
}
It was interesting task for me, so this is what i have written
class Program
{
static void Main(string[] args)
{
string jsonFilePath = #"test.json"; //path to your json
string json = File.ReadAllText(jsonFilePath);
var data = JObject.Parse(json);
CheckJson(data);
Console.ReadLine();
}
static void CheckJson(JToken value)
{
if (value.Values().Count() != 0) //if more than 0 - so value is object or array and we have to call this method for each property
{
foreach (var item in value.Values().ToList())
{
CheckJson(item);
}
}
else if (true) //else - we have exactly value of key, which we can check, for example if . exists or additional checks
{
if (value.Parent.Parent is JObject jObject && jObject["validate"] == null) //check if above "required" property exists
{
jObject.Add("validate", JObject.FromObject(new { required = true })); //add required property
}
}
}
}
This code will add in each object property "required" if it is not exists.
All you need - just add Validation method and call it in if block.
And better to add additional validation that won't continue checking all properties if "required" property exists
I have a datatable that is being populated via serverside ajax. I need to pass variables to the serverside C# method. The variables are not getting to the serverside.
I've tried a few different approaches. It should be pretty easy.
var tblApplication = $('#tblApplication').DataTable({
"ajax": {
"url": '../../Search/ApplicationList',
"type": 'POST',
"data":{
yearh: 2014,
make: ''
}
},
"autoWidth": false,
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
$(nRow).addClass("parent");
return nRow;
},
"order": [[1, "desc"]],
"deferRender": true,
"columns": [
{
"title": '',
"class": 'details-control',
"orderable": false,
"data": null,
"defaultContent": '<img src="../../assets/images/details_open.png" />'
},
{ "title": 'ApplicationId', "data": 'ApplicationId', "visible": false },
{ "title": 'Year', "data": 'Year' },
{ "title": 'Make', "data": 'Make' },
{ "title": 'Model', "data": 'Model' },
{ "title": 'Qualifier', "data": 'Qualifier' },
{ "title": 'Axle', "data": 'Axle' },
{ "title": 'Pad Set', "data": 'PadSet' },
{ "title": 'Side', "data": 'Side' },
{ "title": 'Part List', "data": 'PartListId' }
]
});
[HttpPost]
public JsonResult ApplicationList(int year = 0, string make = null )
{
}
According to datatables.js reference you need to extend "data" something like following to make it work;
$('#example').dataTable( {
"ajax": {
"url": "data.json",
"data": function ( d ) {
return $.extend( {}, d, {
"extra_search": $('#extra').val(),
"year": 2014,
"make": 'Nissan'
} );
}
}
} );
For further documentation please see the this. Hope this helps.
I am having difficulty in binding JSON data to constuct a data table.
My JSON is of the following:
[
{
"ID": 1,
"Number": "2",
"Name": "Avinash"
},
{
"ID":2,
"Number":"21",
"Name":"XYZ"
},
{
"ID": 3,
"Number": "20",
"Name": "KRR"
}
]
I am binding this to jquery datatable as below:
$(document).ready(function () {
$('#table_id').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": '<%:Url.Action("LoadData","Home")%>'
});
$('#table_id').css("width", "100%")
});
My Table Structure is as follows:
<table id="table_id" border="0" class="display" cellpadding="1" cellspacing="1" align="center">
<thead>
<tr>
<th>ID</th>
<th>Number</th>
<th>Name</th>
</tr>
</thead>
</table>
I am getting error as follows:
Datatables Warning(tableid="table_id"):Requested Unknown Parameter'0' from the datasource for row 0
please help..
public ActionResult LoadData()
{
var Data = new DataTable();
Data=DataModel.LoadData();
var JsonData = JsonConvert.SerializeObject(Data, Formatting.None);
return Json(new
{
aaData = JsonData
}, JsonRequestBehavior.AllowGet);
}
After a short investigation, since your JSON is objects, you should supply the columns definition -
json:
{ "aaData": [
{
"ID": 1,
"Number": "2",
"Name": "Avinash"
},
{
"ID":2,
"Number":"21",
"Name":"XYZ"
},
{
"ID": 3,
"Number": "20",
"Name": "KRR"
}
]}
js:
var oTable = $('#table').dataTable({
"bProcessing": true,
"sAjaxSource": '<%:Url.Action("LoadData","Home")%>',
"aoColumns": [
{ "mData": "ID" },
{ "mData": "Number" },
{ "mData": "Name" }
]
});
See example in datatables source under ajax/objects.html.