How to define the name of the data for the ajax.datatable column name? I keep getting the unknow parameter error for ajax.datatable - asp.net-core

JobProg.js
var dataTable;
$(document).ready(function () {
loadDataTable();
});
function loadDataTable() {
dataTable = $('#tblData').DataTable({
"ajax": {
"url": "/Admin/CMJobProg/GetAll"
},
"columns": [
{ "data": "jobnumber", "width": "35%" },
{ "data": "assignfrom", "width": "35%" },
{ "data": "assignto", "width": "35%" },
{ "data": "dateassign", "width": "35%" },
{ "data": "jobaction", "width": "35%" },
{ "data": "remarks", "width": "35%" },
{ "data": "type", "width": "35%" },
{ "data": "division" ,"width": "35%" }
]
})
}
CMJobProg.cs
namespace LXG.Models
{
[Table("CMJOBPROG", Schema = "LASIS")]
public class CMJobProg
{
[Required]
[MaxLength(8)]
[Display(Name = "Job Number")]
[Column("JOB_NUMBER")]
public string JobNumber { get; set; }
[Display(Name = "Assign From")]
[MaxLength(22)]
[Column("ASSIGN_FROM")]
public string AssignFrom { get; set; }
[Display(Name = "Assign To")]
[MaxLength(22)]
[Column("ASSIGN_TO")]
public string AssignTo { get; set; }
[Column("DATE_ASSIGN")]
public DateTime DateAssign { get; set; }
[Display(Name = "Job Action")]
[Range(0, 999)]
[Column("JOB_ACTION")]
public int? JobAction { get; set; }
[Display(Name = "Remarks")]
[MaxLength(500)]
[Column("REMARKS")]
public string Remarks { get; set; }
[Display(Name = "Job Type")]
[Required]
[MaxLength(2)]
[Column("TYPE")]
public string Type { get; set; }
[MaxLength(2)]
[Column("DIVISION")]
public string Division { get; set; }
}
}
DataTables warning: table id=tblData - Requested unknown parameter 'jobnumber' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
I keep getting this error, how to fix this? I able to get the data remarks, type and division, but i cant get others data. Acutally how to define the name for the data name?

As far as I know, asp.net core returned json will has a special format. Like this : JobNumber to jobNumber. To solve this issue. I suggest you could set a JsonPropertyName attribute for each model property.
More details, you could refer to below codes:
[Table("CMJOBPROG", Schema = "LASIS")]
public class CMJobProgress
{
[Required]
[MaxLength(8)]
[Display(Name = "Job Number")]
[Column("JOB_NUMBER")]
[JsonPropertyName("jobnumber")]
public string JobNumber { get; set; }
[Display(Name = "Assign From")]
[MaxLength(22)]
[Column("ASSIGN_FROM")]
[JsonPropertyName("assignfrom")]
public string AssignFrom { get; set; }
[Display(Name = "Assign To")]
[MaxLength(22)]
[Column("ASSIGN_TO")]
[JsonPropertyName("assignto")]
public string AssignTo { get; set; }
[Column("DATE_ASSIGN")]
[JsonPropertyName("dateassign")]
public DateTime DateAssign { get; set; }
[Display(Name = "Job Action")]
[Range(0, 999)]
[Column("JOB_ACTION")]
[JsonPropertyName("jobaction")]
public string JobAction { get; set; }
[Display(Name = "Remarks")]
[MaxLength(500)]
[Column("REMARKS")]
[JsonPropertyName("remarks")]
public string Remarks { get; set; }
[Display(Name = "Job Type")]
[Required]
[MaxLength(2)]
[Column("TYPE")]
[JsonPropertyName("type")]
public string Type { get; set; }
[MaxLength(2)]
[Column("DIVISION")]
[JsonPropertyName("division")]
public string Division { get; set; }
}
Result:

Follow case-sensitive column name in your model/entity class. For example,
"data": "jobnumber"
to
"data": "JobNumber"
Add this "AddNewtonsoftJson" in Startup.cs
services.AddControllersWithViews().AddRazorRuntimeCompilation().AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});

Related

Cannot deserialize the current JSON object Cannot deserialize the current JSON object with group column

I am calling the API and trying to store the Jsonresult into a IEnumerable model class. The json result has group header column consolidated_weather.
when I run the program the following error is coming
JsonSerializationException: Cannot deserialize the current JSON object into type 'System.Collections.Generic.IEnumerable`.
How can I call the given json result into the IEnumerable model class after avoiding group header from json result.
I am using the following two model.
public class Weather
{
[Key]
public long id { get; set; }
public string weather_state_name { get; set; }
public string weather_state_abbr { get; set; }
public string wind_direction_compass { get; set; }
public DateTime created { get; set; }
public DateTime applicable_date { get; set; }
public decimal min_temp { get; set; }
public decimal max_temp { get; set; }
public decimal the_temp { get; set; }
public double wind_speed { get; set; }
public decimal wind_direction { get; set; }
public decimal air_pressure { get; set; }
public decimal Humidity { get; set; }
public string Visibllity { get; set; }
public decimal Predictability { get; set; }
}
public class WeatherList
{
public IEnumerable<Weather> consolidated_weather { get; set; }
}
public async Task<IEnumerable<Weather>> GetWeatherAsync(string woied)
{
var url = SD.APIBaseUrl + woied;
var request = new HttpRequestMessage(HttpMethod.Get, url);
var client = _clientFactory.CreateClient();
HttpResponseMessage response = await client.SendAsync(request);
IEnumerable<Weather> weather = new List<Weather>();
WeatherList weatherList = new WeatherList();
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var jsonString = await response.Content.ReadAsStringAsync();
weatherList = JsonConvert.DeserializeObject<WeatherList>(jsonString);
return weatherList;
}
return null;
}
The API result is coming as
<!-- language: lang-html -->
{
"consolidated_weather": [
{
"id": 4577625064341504,
"weather_state_name": "Heavy Rain",
"weather_state_abbr": "hr",
"wind_direction_compass": "WSW",
"created": "2020-07-14T19:35:14.577740Z",
"applicable_date": "2020-07-14",
"min_temp": 11.11,
"max_temp": 15.05,
"the_temp": 14.32,
"wind_speed": 6.570953330777592,
"wind_direction": 254.13274105640758,
"air_pressure": 1016.5,
"humidity": 85,
"visibility": 7.654361031575599,
"predictability": 77
},
{
"id": 4896540210495488,
"weather_state_name": "Showers",
"weather_state_abbr": "s",
"wind_direction_compass": "WNW",
"created": "2020-07-14T19:35:17.569534Z",
"applicable_date": "2020-07-15",
"min_temp": 12.31,
"max_temp": 17.03,
"the_temp": 16.509999999999998,
"wind_speed": 7.600821124862802,
"wind_direction": 284.49357944800784,
"air_pressure": 1015.5,
"humidity": 82,
"visibility": 13.558008729022509,
"predictability": 73
},
]
"title": "Texas",
"location_type": "City",
"timezone": "US"
<!-- end snippet -->
From your json string, we can see that there is a list of weather object in object consolidated_weather.
So you need to parse json to WeatherList.
public class WeatherList {
public IEnumerable<Weather> consolidated_weather { get; set; }
}
[HttpPost("/weather")]
public async Task<IEnumerable<Weather>> GetWeatherAsync()
{
string jsonString = "{\"consolidated_weather\":[{\"id\":4577625064341504,\"weather_state_name\":\"Heavy Rain\",\"weather_state_abbr\":\"hr\",\"wind_direction_compass\":\"WSW\",\"created\":\"2020-07-14T19:35:14.577740Z\",\"applicable_date\":\"2020-07-14\",\"min_temp\":11.11,\"max_temp\":15.05,\"the_temp\":14.32,\"wind_speed\":6.570953330777592,\"wind_direction\":254.13274105640758,\"air_pressure\":1016.5,\"humidity\":85,\"visibility\":7.654361031575599,\"predictability\":77},{\"id\":4896540210495488,\"weather_state_name\":\"Showers\",\"weather_state_abbr\":\"s\",\"wind_direction_compass\":\"WNW\",\"created\":\"2020-07-14T19:35:17.569534Z\",\"applicable_date\":\"2020-07-15\",\"min_temp\":12.31,\"max_temp\":17.03,\"the_temp\":16.509999999999998,\"wind_speed\":7.600821124862802,\"wind_direction\":284.49357944800784,\"air_pressure\":1015.5,\"humidity\":82,\"visibility\":13.558008729022509,\"predictability\":73}]}";
IEnumerable<Weather> weather = new List<Weather>();
WeatherList weatherList = new WeatherList();
weatherList = JsonConvert.DeserializeObject<WeatherList>(jsonString);
return weatherList.consolidated_weather;
}
Test Result
UPDATE
public class WeatherList
{
public IEnumerable<Weather> consolidated_weather { get; set; }
public string title { get; set; }
public string location_type { get; set; }
public string timezone { get; set; }
}
There are two missings in your json string:
<!-- language: lang-html -->
{
"consolidated_weather": [
{
"id": 4577625064341504,
...
},
{
"id": 4896540210495488,
...
},
] <!-- missing , -->
"title": "Texas",
"location_type": "City",
"timezone": "US"
<!-- missing } -->
<!-- end snippet -->
Assuming that you cannot change the content of the Json, you can create a ConsolidatedWeather class that contains the List of Weathers
public class ConsolidatedWeather
{
public List<Weather> Consolidated_Weather { get; set; }
}
and in your deserialize part
return JsonConvert.DeserializeObject<ConsolidatedWeather>(jsonString).Consolidated_Weather;

How Web API Return Nested JSON Values by HttpPost call from database?

I dont have any problems but i don't know how API call data Nested Values
My Web API have Controller, Models and DataAccess that i call by use sql to call data
I want API call JSON Data format similar as below :
[
{
"Agent_Code": "123456",
"Name": "Miss Sara Manger",
"NickName": "Sara",
"BirthDay": "19690825",
"CardID": "9999999999",
"Address": "870 Goldleaf Lane Lyndhurst NJ New Jersey 07071",
"Mobile": "000000000",
"Email": "utv9hgn3h0k#classesmail.com",
"Bank": [
{
"AcctName": "Miss Sara Manger",
"Acctno": "9999999999",
"Bank": "KBANK"
}
]
}
]
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Testdata.APIs
{
public class DashController : BaseApiController
{
[HttpPost]
public List<Models.AgentDto> TestJSON(Models.CountDashReq model)
{
DataAccess.DashDAL dal = new DataAccess.DashDAL();
List<Models.AgentDto> models = dal.TestJSON(model);
return models;
}
}
Model AgentDto And BankDto:
public class AgentDto
{
public string Agent_Code { get; set; }
public string Name { get; set; }
public string NickName { get; set; }
public string BirthDay { get; set; }
public string CardID { get; set; }
public string Address { get; set; }
public string Mobile { get; set; }
public string Email { get; set; }
public string Bank { get; set; }
}
public class BankDto
{
public string AcctName { get; set; }
public string Acctno { get; set; }
public string Bank { get; set; }
}
DataAccess:
public List<Models.AgentDto> TestJSON(Models.CountDashReq model)
{
string sql = "[dbo].[tb_Json_Get]";
List<Models.AgentDto> result = new List<Models.AgentDto>();
if (model != null)
{
List<SqlParameter> reqParam = new List<SqlParameter>();
//reqParam.Add(new SqlParameter("#usrLogin", model.usrLogin));
DataSet ds = this.Execute(sql, CommandType.StoredProcedure, reqParam.ToArray(), false);
if (ds.Tables.Count > 0)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
Models.AgentDto paramslist = DataAccessUtility.DataTableExtensions.AsEnumerable<Models.AgentDto>(row);
result.Add(paramslist);
}
}
}
return result;
}
Please help me to use Case-when Thank you very much
If you getting request JSON as:
[
{
"Agent_Code": "123456",
"Name": "Miss Sara Manger",
"NickName": "Sara",
"BirthDay": "19690825",
"CardID": "9999999999",
"Address": "870 Goldleaf Lane Lyndhurst NJ New Jersey 07071",
"Mobile": "000000000",
"Email": "utv9hgn3h0k#classesmail.com",
"Bank": [
{
"AcctName": "Miss Sara Manger",
"Acctno": "9999999999",
"Bank": "KBANK"
}
]
}
]
Then the CountDashReq class should be:
public class Bank
{
public string AcctName { get; set; }
public string Acctno { get; set; }
public string Bank { get; set; }
}
public class CountDashReq
{
public string Agent_Code { get; set; }
public string Name { get; set; }
public string NickName { get; set; }
public string BirthDay { get; set; }
public string CardID { get; set; }
public string Address { get; set; }
public string Mobile { get; set; }
public string Email { get; set; }
public List<Bank> Bank { get; set; }
}
In controller method:
[HttpPost]
public List<Models.AgentDto> TestJSON(IList<Models.CountDashReq> model)
{
// Your code
}

Iincomplete validation

There is a model:
public class Model
{
[Required(AllowEmptyStrings = false)]
public string Code { get; set; }
[Required(AllowEmptyStrings = false)]
public string Name { get; set; }
[MaxLength(6), MinLength(6)]
public string Color { get; set; }
[MaxLength(3)]
public string Text { get; set; }
[Required]
public int? User { get; set; }
}
If I pass null data in the User, Color, and Text fields, then the answer is:
{
"code": "VALIDATION",
"fields": [
{
"field": "user",
"error": "REQUIRED"
}
]
}
Why I do not get a complete list of required fields?

response deserialize using json.net returns null

I have the following json:
{
"13377": {
"id": 13377,
"orderId": 13377,
"executionStatus": "-1",
"comment": "",
"htmlComment": "",
"cycleId": -1,
"cycleName": "Ad hoc",
"versionId": 10001,
"versionName": "Version2",
"projectId": 10000,
"createdBy": "vm_admin",
"modifiedBy": "vm_admin",
"assignedTo": "user1",
"assignedToDisplay": "user1",
"assignedToUserName": "user1",
"assigneeType": "assignee",
"issueId": 10013,
"issueKey": "SAM-14",
"summary": "Test",
"label": "",
"component": "",
"projectKey": "SAM",
"folderId": 233,
"folderName": "testfolder"
}
}
I create the following classes using json2csharp and get:
public class __invalid_type__13377
{
public int id { get; set; }
public int orderId { get; set; }
public string executionStatus { get; set; }
public string comment { get; set; }
public string htmlComment { get; set; }
public int cycleId { get; set; }
public string cycleName { get; set; }
public int versionId { get; set; }
public string versionName { get; set; }
public int projectId { get; set; }
public string createdBy { get; set; }
public string modifiedBy { get; set; }
public string assignedTo { get; set; }
public string assignedToDisplay { get; set; }
public string assignedToUserName { get; set; }
public string assigneeType { get; set; }
public int issueId { get; set; }
public string issueKey { get; set; }
public string summary { get; set; }
public string label { get; set; }
public string component { get; set; }
public string projectKey { get; set; }
public int folderId { get; set; }
public string folderName { get; set; }
}
public class RootObject
{
public __invalid_type__13377 __invalid_name__13377 { get; set; }
}
When I deserialize in C# I receive no error but I get null?
Not sure how to approach this..any suggestions would be welcome.
thankyou.
Your Json object can be deserialized with an Dictionary. On this case, you can build your DataObject like you are doing:
public class Foo
{
public int id { get; set; }
public int orderId { get; set; }
...
}
And Deserialize to
Dictionary<string, Foo>
If you are using Newtonsoft:
var data = JsonConvert.DeserializeObject<Dictionary<string,Foo>(json);
You can use sometimes, when the type of object is unknown, the dynamic keyword:
var data = JsonConvert.DeserializeObject<dynamic>(json);

Box V2 API - Where is lock/unlock?

There is a note in the developer road map from December of 2013 saying, "Lock/Unlock – We’ve added support for locking and unlocking files into the V2 API."
I've been all through the V2 API (for c#) and cannot find it anywhere. I expected to find something in the BoxFilesManager class or as something you would pass to UpdateInformationAsync within the BoxFileRequest class.
So is there a way to lock/unlock a file?
Great question. In order to see the current lock status of a file do a
GET https://api.box.com/2.0/files/7435988481/?fields=lock
If there is no lock on the file, you'll get something like this back:
{
"type": "file",
"id": "7435988481",
"etag": "0",
"lock": null
}
If you want to lock a file, you need to do a PUT (update) on the /files/ endpoint with a body that tells us what type of lock, and when to release it. Like this:
PUT https://api.box.com/2.0/files/7435988481/?fields=lock
{"lock": {
"expires_at" : "2014-05-29T19:03:04-07:00",
"is_download_prevented": true
}
}
You'll get a response confirming your lock was created:
{
"type": "file",
"id": "7435988481",
"etag": "1",
"lock": {
"type": "lock",
"id": "14516545",
"created_by": {
"type": "user",
"id": "13130406",
"name": "Peter Rexer gmail",
"login": "prexer#gmail.com"
},
"created_at": "2014-05-29T18:03:04-07:00",
"expires_at": "2014-05-29T19:03:04-07:00",
"is_download_prevented": true
}
}
Since there isn't a lock/unlock yet, I created a Lock Manager based on the existing managers:
class BoxCloudLockManager : BoxResourceManager
{
#region Lock/Unlock Classes
[DataContract]
internal class BoxLockRequestInfo
{
[DataMember(Name = "status")]
public string Status { get; set; }
//[DataMember(Name = "expires_at")]
//public string ExpiresAt { get; set; }
[DataMember(Name = "is_download_prevented")]
public bool IsDownloadPrevented { get; set; }
}
[DataContract]
internal class BoxLockRequest
{
[DataMember(Name = "lock")]
public BoxLockRequestInfo Lock { get; set; }
}
#endregion
const string LockFileString = "{0}/?fields=lock";
public BoxCloudLockManager(IBoxConfig config, IBoxService service, IBoxConverter converter, IAuthRepository auth)
: base(config, service, converter, auth)
{
}
public async Task<BoxLockInfo> LockAsync(string documentId,bool isDownloadPrevented = true)
{
var lockRequest = new BoxLockRequest { Lock = new BoxLockRequestInfo { Status = "lock", IsDownloadPrevented = isDownloadPrevented } };
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(LockFileString, documentId))
.Method(RequestMethod.Put)
.Payload(_converter.Serialize(lockRequest));
IBoxResponse<BoxLockInfo> response = await ToResponseAsync<BoxLockInfo>(request).ConfigureAwait(false);
return response.ResponseObject;
}
public async Task<BoxLockInfo> UnlockAsync(string documentId)
{
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(LockFileString, documentId))
.Method(RequestMethod.Put)
.Payload("{\"lock\":null}");
IBoxResponse<BoxLockInfo> response = await ToResponseAsync<BoxLockInfo>(request).ConfigureAwait(false);
return response.ResponseObject;
}
public async Task<BoxLockInfo> GetLockInfoAsync(string documentId)
{
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(LockFileString, documentId))
.Method(RequestMethod.Get);
IBoxResponse<BoxLockInfo> response = await ToResponseAsync<BoxLockInfo>(request).ConfigureAwait(false);
return response.ResponseObject;
}
}
I derived a class from BoxClient, adding a LockManager and instantiate it within the Constructor.
Here is the Lock Info:
[DataContract]
public class BoxLockedBy
{
[DataMember(Name = "type")]
public string Type { get; set; }
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "login")]
public string Login { get; set; }
}
[DataContract]
public class BoxLockDetails
{
[DataMember(Name = "type")]
public string Type { get; set; }
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "created_by")]
public BoxLockedBy CreatedBy { get; set; }
[DataMember(Name = "created_at")]
public string CreatedAt { get; set; }
[DataMember(Name = "expires_at")]
public string ExpiresAt { get; set; }
[DataMember(Name = "is_download_prevented")]
public bool IsDownloadPrevented { get; set; }
}
[DataContract]
public class BoxLockInfo
{
[DataMember(Name = "type")]
public string Type { get; set; }
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "etag")]
public string Etag { get; set; }
[DataMember(Name = "lock")]
public BoxLockDetails LockDetails { get; set; }
}