Generating array of arrays - javascript

I have a Web-API method that is returning JSON and I want the array structure to look like this:
[ [123, 1.1], [222, 3.9] ]
My Web API controller is returning JSON in the following format:
[{"CreatedDate":1314736440,"Reading":20.0}, "CreatedDate":1314779640,"Reading":7.9}]
Web API Controller:
[HttpGet]
public HttpResponseMessage AllJson()
{
using (var ctx = new SomeContext())
{
var records = ctx.DataX.ToList();
var dtos = Mapper.Map<...>(records);
return new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(JsonConvert.SerializeObject(dtos), Encoding.UTF8, "application/json")
};
}
}
DTO
public class DtoModel
{
public int CreatedDate { get; set; }
public double Reading { get; set; }
}
Sample Javascipt:
var seriesData = [];
$.getJSON("api/xxx/AllJson ", function (data) {
$.each(data, function (key, val) {
seriesData.push(val.CreatedDate.toString() + " ," + val.Reading.toString());
console.log(val.CreatedDate + " ," + val.Reading);
});
});

You need to create an a single array containing many arrays of length 2.
See this code:
$.getJSON("api/xxx/AllJson")
.done(function (data) {
var processedJson = new Array();
$.map(data, function (obj, i) {
processedJson.push([obj.CreatedDate, obj.Reading]);
});
FunctionToDoSomethingWithYourDataStructure(processedJson);
});

I think this might solve your problem..
structure wise, this should look like [[a,b],[c,d]];
var createSeriesData = function(){
seriesData = [];
JSON_obj = JSON.parse('[{"CreatedDate":1314736440,"Reading":20.0},{"CreatedDate":1314779640,"Reading":7.9}]');
for(var key in JSON_obj){
if(JSON_obj.hasOwnProperty(key)){
seriesData[key] = [];
seriesData[key].push(JSON_obj[key].CreatedDate.toString());
seriesData[key].push(JSON_obj[key].Reading.toString());
}
}
console.log(seriesData);
}

Related

Parameter sent to ASP NET Core Controller from AJAX call is null if it's too large?

I have AJAX code in my page which calls an ASP.NET Core controller. The code sends a list of objects to the controller. When the list is short enough, say 8 objects, the fundFindingsGridRows parameter is properly set to the data, however, when longer, this parameter is null.
I have tried setting several things in my Startup.cs but nothing has worked. Is there some other setting that I can configure to get this to accept larger amounts of data? Is there another issue other than size at play here?
Startup.cs (pertinent code):
services.AddMvc(options =>
{
options.MaxModelBindingCollectionSize = 100000;
});
services.Configure<FormOptions>(options =>
{
options.ValueCountLimit = int.MaxValue;
options.ValueLengthLimit = int.MaxValue;
options.MultipartHeadersLengthLimit = int.MaxValue;
});
services.Configure<IISServerOptions>(options =>
{
options.MaxRequestBodySize = int.MaxValue;
});
Javascript AJAX code:
var DATA = new Array();
var grid = $("#V3FundFindingsByBuildingGrid").data("kendoGrid");
var dataTable = grid.dataSource;
$.each(grid.items(), function (index, item) {
var id = $(item).data('uid');
var dataItem = dataTable.getByUid(id);
var building = {};
building.PANumber = dataItem.PANumber,
building.employerNo = dataItem.employerNo,
building.billToEntityNo = dataItem.billToEntityNo,
building.accountNo = dataItem.AccountNo,
building.revisionDateExists = #Model.revisionDateExists.ToString().ToLower(),
building.settlement = false,
building.health = dataItem.Health,
building.pension = dataItem.Pension,
building.annuity = dataItem.Annuity,
building.legal = dataItem.Legal,
building.training = dataItem.Training,
building.joint = dataItem.Joint,
building.four01k = dataItem.Four01k,
building.healthInterest = dataItem.HealthInterest,
building.pensionInterest = dataItem.PensionInterest,
building.annuityInterest = dataItem.AnnuityInterest,
building.legalInterest = dataItem.LegalInterest,
building.trainingInterest = dataItem.TrainingInterest,
building.jointInterest = dataItem.JointInterest,
building.four01kInterest = dataItem.Four01kInterest
DATA.push(building);
});
var fundFindingsGridRows = JSON.stringify(DATA);
$.ajax({
type: "POST",
url: "/PayrollAudit/SaveFundFindings",
data: fundFindingsGridRows,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$('#FindingsByBuildingDiv').html(response);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
Controller Action:
[RequestSizeLimit(100_000_000)]
public IActionResult SaveFundFindings([FromBody]List<FundFindingsGridRow> fundFindingsGridRows)
{...}
Data from the Header:
Parsed payload snippet:
So I found away to solve this issue. What I did was to not send the data to the controller as JSON, and instead of as an array of objects. I also removed the contentType and dataType settings from the AJAX call, and changed the data setting:
var DATA = new Array();
var grid = $("#V3FundFindingsByBuildingGrid").data("kendoGrid");
var dataTable = grid.dataSource;
$.each(grid.items(), function (index, item) {
var id = $(item).data('uid');
var dataItem = dataTable.getByUid(id);
var FundFindingsGridRow = {};
FundFindingsGridRow.PANumber = dataItem.PANumber,
FundFindingsGridRow.employerNo = dataItem.employerNo,
FundFindingsGridRow.billToEntityNo = dataItem.billToEntityNo,
FundFindingsGridRow.accountNo = dataItem.AccountNo,
FundFindingsGridRow.revisionDateExists = #Model.revisionDateExists.ToString().ToLower(),
FundFindingsGridRow.settlement = false,
FundFindingsGridRow.health = dataItem.Health,
FundFindingsGridRow.pension = dataItem.Pension,
FundFindingsGridRow.annuity = dataItem.Annuity,
FundFindingsGridRow.legal = dataItem.Legal,
FundFindingsGridRow.training = dataItem.Training,
FundFindingsGridRow.joint = dataItem.Joint,
FundFindingsGridRow.four01k = dataItem.Four01k,
FundFindingsGridRow.healthInterest = dataItem.HealthInterest,
FundFindingsGridRow.pensionInterest = dataItem.PensionInterest,
FundFindingsGridRow.annuityInterest = dataItem.AnnuityInterest,
FundFindingsGridRow.legalInterest = dataItem.LegalInterest,
FundFindingsGridRow.trainingInterest = dataItem.TrainingInterest,
FundFindingsGridRow.jointInterest = dataItem.JointInterest,
FundFindingsGridRow.four01kInterest = dataItem.Four01kInterest
DATA.push(FundFindingsGridRow);
});
$.ajax({
type: "POST",
url: "/PayrollAudit/SaveFundFindings",
data: { 'fundFindingsGridRows': DATA },
success: function (response) {
$('#FindingsByBuildingDiv').html(response);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
Not sure what the issue was with the JSON. If someone can let me know, I'd appreciate it in case I run across an instance where JSON is required in the future!
Below is a work demo that can send the data to the controller as JSON, you can refer to it.
Student:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Name2 { get; set; }
public string Name3 { get; set; }
public string Name4 { get; set; }
public string Name5 { get; set; }
public string Name6 { get; set; }
public string Name7 { get; set; }
public string Name8 { get; set; }
public string Name9 { get; set; }
public string Name10 { get; set; }
}
HomeController:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index([FromBody] List<Student> student)
{
return View();
}
}
Index view:
<button onclick="postdata1()">submit(jsondata)</button>
#section scripts{
<script type="text/javascript">
function postdata1() {
var a = new Array();
for (var i = 0; i < 100000; i++) {
var indexViewModel = {};
indexViewModel.Id = i;
indexViewModel.Name = "name" + i;
indexViewModel.Name2 = "name2" + i;
indexViewModel.Name3 = "name3" + i;
indexViewModel.Name4 = "name4" + i;
indexViewModel.Name5 = "name5" + i;
indexViewModel.Name6 = "name6" + i;
indexViewModel.Name7 = "name7" + i;
indexViewModel.Name8 = "name8" + i;
indexViewModel.Name9 = "name9" + i;
indexViewModel.Name10 ="name10" + i;
a.push(indexViewModel);
}
var data = JSON.stringify(a);
$.ajax({
type: "POST",
url: '/home/Index',
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
}).done(function (data) {
});
}
</script>
}
result:

JSON data null in controller

I am working to send multiple email/SMS by selecting the checkbox. And When I am receiving in my javascript function it's getting with data. But when I pass it to action method record count shows but all data are null. Below is my code with screenshot here
Here it is my Model:
public class BulkEmailSendViewModel
{
public BulkEmailSendViewModel()
{
Candidates = new List<CandidateData>();
}
public List<CandidateData> Candidates { get; set; }
public string Body { get; set; }
public string Subject { get; set; }
}
public class CandidateData
{
public string Email { get; set; }
public string CandidateId { get; set; }
public string Phone { get; set; }
public string CandidateName { get; internal set; }
}
//Select all selected checkbox
$("#bulkAction").change(function () {
var ddlId = $("#bulkAction").val();//to get sms or email
var chk_arr = $('.checkCandidate:checkbox:checked');
var chklength = chk_arr.length;
var json = '';
$('.checkCandidate:checkbox:checked').each(function () {
if (this.checked) {
var Phone = $(this).attr("candidatePhone");
var CandidateId = $(this).attr("candidateId");
var Email = $(this).attr("candidatEmail");
var item = '{\"Phone\":\"' + Phone + '\","CandidateId\":\"' + CandidateId + '\",\"Email\":\"' + Email + '\",\"CandidateName\":\"\"},';
json += item;
}
});
json = "[" + json.substr(0, json.length - 1) + "]";
SendBulkEmail(json);
});
My Javascript:
function SendBulkEmail(jsonObj) {
alert(jsonObj);
if (jsonObj.length > 0) {
var send = "/Utility/Notifications/BulkEmail";
$(".modal-title").text("Send Email");
//var data = {
// Candidates: eval(jsonObj)
//};
$.get(send, { bulkEmailSendViewModel: eval(jsonObj) }, function (result) {
$("#C_modal_body").html("");
$("#C_modal_body").html(result);
});
}
else {
$.alert("Email not found for this candidate.");
// e.stopPropagation();
}
}
My Controller:
public PartialViewResult BulkEmail(List<CandidateData> bulkEmailSendViewModel)
{
BulkEmailSendViewModel bulkDetail = new BulkEmailSendViewModel();
return PartialView(bulkDetail);
}
Why my all values are null even I am getting in javascript function?
change your javascript codes to this:
$("#bulkAction").change(function () {
var ddlId = $("#bulkAction").val();//to get sms or email
var chk_arr = $('.checkCandidate:checkbox:checked');
var chklength = chk_arr.length;
var data = [];
$('.checkCandidate:checkbox:checked').each(function () {
if (this.checked) {
var Phone = $(this).attr("candidatePhone");
var CandidateId = $(this).attr("candidateId");
var Email = $(this).attr("candidatEmail");
var item = {Phone: Phone,
CandidateId: CandidateId,
Email : Email,
CandidateName : ""};
data.push(item);
}
});
SendBulkEmail(data);
});
and the SendBulkEmail to:
function SendBulkEmail(data) {
if (data.length > 0) {
var send = "/Utility/Notifications/BulkEmail";
$(".modal-title").text("Send Email");
//var data = {
// Candidates: eval(jsonObj)
//};
$.post(send, { bulkEmailSendViewModel: JSON.stringify(data) }, function (result) {
$("#C_modal_body").html("");
$("#C_modal_body").html(result);
});
}
else {
$.alert("Email not found for this candidate.");
// e.stopPropagation();
}
}
and finally:
[HttpPost]
public PartialViewResult BulkEmail(List<CandidateData> bulkEmailSendViewModel)
{
BulkEmailSendViewModel bulkDetail = new BulkEmailSendViewModel();
return PartialView(bulkDetail);
}
In your controller, I don't see any use of the bulkEmailSendViewModel input parameter.
Maybe, you could propagate the candidate list as follow:
public PartialViewResult BulkEmail(List<CandidateData> candidates)
{
BulkEmailSendViewModel bulkDetail=new BulkEmailSendViewModel();
bulkDetail.candidates = candidates;
return PartialView(bulkDetail);
}

Converting JSON object into C# list

Before posting this question I tried other related posts but it didn't work out, so posting here.
I have got a Json stored in a hidden field that I am accessing in code behind file of my Mark-up page. I need to convert this Json into List and bind it to a grid, but while de-serializing it throws error saying "Unexpected error encountered while parsing values ''".
Script for getting data from grid and making a Json object.
function BeforeSorting() {
var list = UpdateDataSource();
$("#SortingField").val(list);
}
function UpdateDataSource() {
var list="";
var grid = $find("DetailsGrid");
var rows = grid.get_rows();
for(var i =0 ; i<rows.get_length();i++){
var name = rows.get_row(i).get_cellByColumnKey("Name").get_value();
var country = rows.get_row(i).get_cellByColumnKey("Country").get_value();
var gender = rows.get_row(i).get_cellByColumnKey("Gender").get_value();
var age = rows.get_row(i).get_cellByColumnKey("Age").get_value();
var uniqueKey = rows.get_row(i).get_cellByColumnKey("UniqueKey").get_value();
list = list + '{"Name":"' + name + '", "Country":"' + country + '", "Gender":"' + gender + '", "Age":' + age + ', "UniqueKey":' + uniqueKey + '},';
}
list = "["+list.substr(0, list.length - 1)+"]";
return JSON.parse(list);
}
The model class:
public class Details
{
public string Name { get; set; }
public string Gender { get; set; }
public string Country { get; set; }
public int UniqueKey { get; set; }
public int Age { get; set; }
}
The code for de-serializing the json and retrieving data as a list of the model class.
protected void DetailsGrid_ColumnSorted(object sender, Infragistics.Web.UI.GridControls.SortingEventArgs e)
{
var dataSource = SortingField.Value;
List<Details> result = (List<Details>)Newtonsoft.Json.JsonConvert.DeserializeObject(dataSource, typeof(List<Details>));
DetailsGrid.DataSource = result;
DetailsGrid.DataBind();
}
The json string as obtained:
"[{"Name":"Jerry", "Country":"U.S.A.", "Gender":"Male", "Age":20, "UniqueKey":1},{"Name":"Tom", "Country":"U.K", "Gender":"Male", "Age":10, "UniqueKey":2},{"Name":"George", "Country":"Gremany", "Gender":"Male", "Age":38, "UniqueKey":3},{"Name":"Kate", "Country":"France", "Gender":"Female", "Age":40, "UniqueKey":4},{"Name":"Jenny", "Country":"Poland", "Gender":"Female", "Age":25, "UniqueKey":5}]"
create list as an array and add items as JavaScript objects and then convert it to JSON using JSON.stringify
function UpdateDataSource() {
var grid = $find("DetailsGrid");
var rows = grid.get_rows();
var list = [];
for(var i =0 ; i < rows.get_length(); i++){
var item = {
Name : rows.get_row(i).get_cellByColumnKey("Name").get_value(),
Country : rows.get_row(i).get_cellByColumnKey("Country").get_value(),
Gender : rows.get_row(i).get_cellByColumnKey("Gender").get_value(),
Age : rows.get_row(i).get_cellByColumnKey("Age").get_value(),
UniqueKey : rows.get_row(i).get_cellByColumnKey("UniqueKey").get_value()
};
list.push(item);
}
return JSON.stringify(list);
}
The code for de-serializing the json and retrieving data as a list of the model class can be refactored to
protected void DetailsGrid_ColumnSorted(object sender, Infragistics.Web.UI.GridControls.SortingEventArgs e) {
var dataSource = SortingField.Value;
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Details>>(dataSource);
DetailsGrid.DataSource = result;
DetailsGrid.DataBind();
}
UPDATE as suggested by #Adnreas should produce the same result.
function UpdateDataSource() {
var grid = $find("DetailsGrid");
var rows = grid.get_rows();
var list = rows.map(function(row) {
return {
Name: row.get_cellByColumnKey("Name").get_value(),
Country: row.get_cellByColumnKey("Country").get_value(),
Gender: row.get_cellByColumnKey("Gender").get_value(),
Age: row.get_cellByColumnKey("Age").get_value(),
UniqueKey: row.get_cellByColumnKey("UniqueKey").get_value()
};
});
return JSON.stringify(list);
}
I think this will do
protected void DetailsGrid_ColumnSorted(object sender, Infragistics.Web.UI.GridControls.SortingEventArgs e)
{
var dataSource = SortingField.Value;
List<Details> result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Details>>(dataSource);
DetailsGrid.DataSource = result;
DetailsGrid.DataBind();
}

Return multiple json objects from controller

I return multiple json objects but i don't know how to return that objects. I want to get returned json objects and send them to ajax request. This is my ActionResult:
public ActionResult AutoCompleteEventName(string eventName)
{
Event ev = new Event();
ev.Name = eventName;
var searchEvent = EventService.Instance.Search(ev);
var totalCount = EventService.Instance.SearchCount(ev);
}
If you want to send object's list, you can do it with this way:
var yourObjectList = EventService.Instance.LoadSomeEvents();
List<object> objectList = new List<object>();
foreach (var event in yourObjectList)
{
objectList.Add(new
{
id = event.Id,
name = event.Name,
});
}
return Json(objectList, JsonRequestBehavior.AllowGet);
return Json(new { searchEvent = searchEvent , totalCount = totalCount }, JsonRequestBehavior.AllowGet)
in controller
return result as below
var returnField = new { searchEvent = "searchEvent", totalCount = totalCount.ToString() };
return Json(returnField, JsonRequestBehavior.AllowGet);
in Ajax Request
success: function (data) {
var searchEvent = data.searchEvent;
var totalCount =data.totalCount
}

Pass JSON object list to action

I have a Model like this in my ASP.NET MVC 2 project,
public class HomeModel
{
public string Name { get; set; }
public int HomeCount { get; set; }
private List<string> _list;
public List<string> List
{
get
{
if (_list == null)
{
_list = new List<string>();
}
return _list;
}
set
{
_list = value;
}
}
private List<ChildModel> _children;
public List<ChildModel> Children
{
get
{
if (_children == null)
{
_children = new List<ChildModel>();
}
return _children;
}
set
{
_children = value;
}
}
}
public class ChildModel
{
public string Address { get; set; }
}
and the script as
var obj = new Object();
obj.Name = "MyName";
obj.HomeCount = 56;
obj.List = new Array();
obj.List[0] = "AAA";
obj.List[1] = "bbb";
var child = new Object();
child.Address = "ccc";
obj.Children = new Array();
obj.Children[0] = child;
var child2 = new Object();
child.Address = "ddd";
obj.Children[1] = child2;
jQuery.ajaxSettings.traditional = true
$.post('/Home/Test',obj, function (data) { });
My problem is even the string list is generated at the controller's action, the object list's count is 0. Can anyone tell how to do this?
When you submit an object as jQuery's ajax payload, it's converted to key/value pairs of data. If this were $.get instead of $.post for example, you'd wind up with
?name=MyName&etc.
This article should get you what you're looking for:
http://www.intelligrape.com/blog/2010/06/11/jquery-send-json-object-with-an-ajax-request/
I'd also recommend json/object literal notation here:
var obj = {
Name: "MyName",
HomeCount: 56,
List:["AAA","bbb"],
child:{
Address: "ccc",
Children:[
//etc
]
}
}
see json.org for specs, and jslint.com/jshint.com for validation.

Categories

Resources