Return object with IEnumerable with AJAX - javascript

I have some problem while getting the object from the controller via AJAX call.To be precise, I would like to get the object which contains property with IEnumerable type.
Class 1 :
public class ChartItem
{
public string cName { get; set; }
public string label { get; set; }
public decimal value { get; set; }
public decimal value2 { get; set; }
public string value2Cur { get; set; }
public string value2Unit { get; set; }
public string color { get; set; }
public string strokeColor { get; set; }
public string chartTitle { get; set; }
}
Class 2 :
public class ReportParameter
{
public string ReportName { get; set; }
public string DateFrom { get; set; }
public string DateTo { get; set; }
public string CountryId { get; set; }
public string RegionId { get; set; }
public string RepresentativeId { get; set; }
public string CustomerId { get; set; }
public ExportFormatType ReportFormat { get; set; }
public EReport.ChartType ChartType { get; set; }
public bool EmailFlag { get; set; }
public IEnumerable<ChartItem> chartItems { get; set; }
}
This is the controller that execute the call :
[HttpPost]
public JsonResult ReloadReportSummary(EReport.ReportParameter rptParam)
{
EMAP.WEB_Bootstrap.Helper.ViewHelper viewHelper = new ViewHelper();
IEnumerable<EReport.ChartItem> resultChart=null;
try
{
EReport.ReportParameter eRpt = new EReport.ReportParameter();
eRpt.ReportName = ((EReport.ReportName)Enum.Parse(typeof(EReport.ReportName), rptParam.ReportName)).ToString();
switch ((EReport.ReportName)Enum.Parse(typeof(EReport.ReportName), rptParam.ReportName))
{
case EReport.ReportName.CRPotentialCustomerList:
//reload the chart data
resultChart =
from cp in db.CustomerProducts
join pr in db.Products on cp.ProductID equals pr.ProductID
group cp by cp.Product.ProductDescription into grp
select new EReport.ChartItem { label = grp.Key, value = grp.Count()};
break;
case EReport.ReportName.CRCustomerProductAppMasterPivot:
//reload the chart data
resultChart =
from cp in db.CustomerProducts
join pr in db.Products on cp.ProductID equals pr.ProductID
group cp by cp.Product.ProductDescription into grp
select new EReport.ChartItem { label = grp.Key, value = grp.Count() };
break;
default:
break;
}
eRpt.chartItems = resultChart;
---EDITED----
var result = eRpt;
return Json(new { Result = "OK", Record = result },
JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { Result = "ERROR"});
}
}
And this is the AJAX call :
$.ajax({
url: urlReportSummary,
data: JSON.stringify(rptParam),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
var len = result.Record.chartItem.length;
},
error: function (ex) {
alert(ex);
}
});
Actually I would like to go through each Record.chartItem's object and do some process there. But somehow the returned record not being recognized. Below is the error :
"TypeError: result.Record.chartItem is undefined".
May I know what is the correct way to get the list of data using AJAX ?
Thanks a lot

Change the success function as below and try
success: function (result) {
var len = result.Record.chartItems.length;
},
You have misspelled the property chartItems. I think now it will work

Related

ASP NET MVC passing ajax list items to controller not working as expected

I am trying to pass a list of objects to Controller using ajax, it works and shows how many items are there but shows items as null and I do not know what I am misisng.
I have this in JavaScript:
var data = {
"expediente": '#Model.NUMEMP',
"edad": '#edad',
"sexo": '#Model.SEXO',
"piezasConNotas": piezasYNotas,
//"servicio": $("#actividades").val(),
//"subServicio": $("#actividadesRealizar").val(),
"diagnostico": $("#diagnosticos").val(),
"interconsulta_esp": "",
"interconsulta": $("#interconsulta").val(),
};
console.log(data);
$.ajax({
'url': ' #Url.Action("AgregarExpedienteDental", "ServiciosMedicos")',
"data": data ,
"success": function (result) {
if (result === "1") {
//swal("Good job!", "You clicked the button!", "success");
Swal.fire('Success', 'Se ha insertado', 'success');
setTimeout('', 3000);
const myTimeout = setTimeout(myGreeting, 1500);
}
},
"error": function (response) {
}
});
this is what console.log(data) shows:
and when I send them to controller this is how it shows in the debugger:
as you can see other data is ok and the count from the list is ok but the items are going inside
as null.
I do not know what I am doing wrong? How do I solve this?
this is my C# code:
public JsonResult AgregarExpedienteDental(ExpedienteDentall data)
{
....
}
public class ExpedienteDentall
{
public string diagnostico { get; set; }
public string edad { get; set; }
public string expediente { get; set; }
public string interconsulta { get; set; }
public string interconsulta_esp { get; set; }
//public string servicio { get; set; } = "";
public string sexo { get; set; }
//public string subServicio { get; set; } = "";
public List<piezasConNotas> piezasConNotas { get; set; }
}
public class piezasConNotas
{
public string diente { get; set; }
public string nota { get; set; }
public string actividad { get; set; }
public string actividadRealizada { get; set; }
}

How to pass an array in formData

I am using formData and trying to pass an array that receives it in .Net Core backend
this is my array that i try to send truck.StateTruck:
{
0: {StaId: 6}
1: {StaId: 7}
2: {StaId: 8}
3: {StaId: 9}
}
this is my method to send my data that I try to send only the StaId and its value:
let formData = new FormData();
formData.set('DriId',truck.DriId);
formData.set('TruExdate',truck.TruExdate);
formData.set('TruAddress',truck.TruAddress);
formData.set('TruCity',truck.TruCity);
formData.set('TraId',truck.TraId);
formData.set('TruZip',truck.TruZip);
formData.set('TruYear',truck.TruYear);
formData.set('TruMake',truck.TruMake);
formData.set('TruType',truck.TruType);
formData.set('TruFuel',truck.TruFuel);
formData.set('TruAxles',truck.TruAxles);
formData.set('TruVin',truck.TruVin);
formData.set('TruDocurl',truck.TruDocurl);
formData.set('TraUnit',truck.TraUnit);
formData.set('TraMake',truck.TraMake);
formData.set('TraYear',truck.TraYear);
formData.set('TtyId',truck.TtyId);
formData.set('TraIntmaterial',truck.TraIntmaterial);
formData.set('TraEquipament',truck.TraEquipament);
formData.set('TraOption',truck.TraOption);
formData.set('Fichero',truck.Fichero);
formData.append('StateTruck',JSON.stringify(truck.StateTruck));
when printing to the console using the console.log (formData.getAll ('StateTruck')); I see
["[{"StaId":6},{"StaId":7},{"StaId":8},{"StaId":9}]"]
and my backend expects this structure:
public class TruckRequest
{
public int TruId { get; set; }
public int? DriId { get; set; }
public DateTime? TruExdate { get; set; }
public string TruAddress { get; set; }
public string TruCity { get; set; }
public int? TraId { get; set; }
public string TruZip { get; set; }
public string TruYear { get; set; }
public string TruMake { get; set; }
public string TruType { get; set; }
public string TruFuel { get; set; }
public string TruAxles { get; set; }
public string TruVin { get; set; }
public string TruDocurl { get; set; }
public string TraUnit { get; set; }
public string TraMake { get; set; }
public string TraYear { get; set; }
public int? TtyId { get; set; }
public string TraIntmaterial { get; set; }
public string TraEquipament { get; set; }
public string TraOption { get; set; }
public IFormFile Fichero { get; set; }
public string TruUregistro { get; set; }
public DateTime? TruUfecha { get; set; }
public string TruUupdate { get; set; }
public DateTime? TruUupdatefecha { get; set; }
public string TruEstado { get; set; }
public virtual ICollection<StateTruck> StateTruck { get; set; }
}
public partial class StateTruck
{
public int SruId { get; set; }
public int? StaId { get; set; }
public string SruUregistro { get; set; }
public DateTime? SruUfecha { get; set; }
public string SruUupdate { get; set; }
public DateTime? SruUupdatefecha { get; set; }
public string SruEstado { get; set; }
public int? TruId { get; set; }
}
How can I give it the correct format so that it can be received?
if you need the value converted to string, you may use
e.g.
formData.set('TruYear', truck.TruYear.toString());
for integer, e.g.
formData.set('TruYear', parseInt(truck.TruYear));
All these are passed as formData to your backend, your server should create the parser to convert to the right format, and to validate it is the right format.
Never, trust, anything submitted from frontend.
When console logging out the data you need to parse the first element in the array received from formData.getAll ('StateTruck'). The following should help in your scenario:
console.log(JSON.parse(formData.getAll("StateTruck")[0]))
According to your description, I assume you want to use FormData to pass value (include the object array) from client side to server side (Web API). If that is the case, you could refer to the following sample code:
Client side (using JQuery Ajax to call the web API method):
$(function () {
//Submit Main Form.
$("#btnCreate").click(function (event) {
//Prevent Default Region.
event.preventDefault();
//define an array to store the StateTruck
var statetruce = new Array();
for (var i = 0; i < 5; i++) {
statetruce.push({ StaId: i });
}
let formData = new FormData();
formData.set('DriId', 101);
formData.set('TruAddress', "Address 1");
formData.set('TruCity', "city A");
formData.set('TraId', 1011);
formData.set('TruZip', "zip12");
formData.set('TruYear', "years ");
formData.append('StateTruck', JSON.stringify(statetruce));
$.ajax({
url: '/api/TestAPI',
type: "post",
async: true,
data: formData,
processData: false,
contentType: false,
success: function (response) {
// window.location.href = response;
}
});
});
});
Based on the Array Object's property to create a View Model, it is used to Deserialize the array object.
Code in the Web API method:
[HttpPost]
public async Task<IActionResult> Post(IFormCollection collection)
{
var DriId = collection["DriId"].ToString();
var TruAddress = collection["TruAddress"].ToString();
var StateTruck = collection["StateTruck"].ToString();
//deserialize the object
var result = System.Text.Json.JsonSerializer.Deserialize<List<StateTruckViewModel>>(StateTruck);
//do something
return Ok("success");
}
Then debug screenshot as below:

Reading Javascript FormData value in Asp.net Web api Httpresponsemessage

I have a Web api which is decorated with [HttpPost] which is used to upload all information passed in parameter but getting this error
Error
Controller
[HttpPost]
public HttpResponseMessage questionnairesubmit(HttpRequestMessage form)
{
//want to get json of "questionlist" which is send from javascript like
var QuestionnaireList = JsonConvert.DeserializeObject<List<outRightLogos.Areas.client.WebApiModel.AttributeValueTB>>(form["questionlist"]);
}
Here is javascript sending Json model with name questionlist this I want to fetch in controller.I read FormData() from Here
Javascript
var data = new FormData();
var QuestionnaireList = [];
QuestionnaireList.push({
FieldID: $(this).attr("data-fieldid"),
attributeID: $(this).attr("data-attributeid"),
attributeValue: $(this).val(),
websitesID: 2,
OrderID: $('#orderid').val(),
orderbitID: $('#orderbidid').val(),
serviceId: $(this).attr("data-serviceid"),
subServiceId: $(this).attr("data-subserviceid"),
IsSubmit: IsSubmit,
});
data.append("questionlist", JSON.stringify(QuestionnaireList));
$.ajax({
type: "POST",
url: path,
contentType: 'application/json',//"application/json; charset=utf-8",
processData: false,
dataType: "json",
data: data,
success: function (result) {
if (result.sucess == "save") {
alert('Your form has been saved.');
}
else if (result.sucess == "Submit") {
alert('Your form has been submitted.');
window.location.href = result.Url;
}
},
error: function (result) {
alert('Oh no ');
}
});
Here is a model class AttributeValueTB
Class
public class AttributeValueTB
{
public long attributeValueID { get; set; }
[Required]
[StringLength(200)]
public string attributeValueCode { get; set; }
public int FieldID { get; set; }
public int attributeID { get; set; }
public string attributeValue { get; set; }
public int websitesID { get; set; }
public long OrderID { get; set; }
public long orderbitID { get; set; }
public long serviceId { get; set; }
public long subServiceId { get; set; }
public string extra1 { get; set; }
public string extra2 { get; set; }
[StringLength(200)]
public string attributeCode { get; set; }
public bool isActive { get; set; }
public bool isShow { get; set; }
public bool IsSubmit { get; set; }
[Column(TypeName = "date")]
public DateTime? createDate { get; set; }
[Column(TypeName = "date")]
public DateTime? modifiedDate { get; set; }
public int? createBy { get; set; }
public int? modifiedBy { get; set; }
[Column(TypeName = "timestamp")]
[MaxLength(8)]
[Timestamp]
public byte[] Timestamp { get; set; }
}
You don't need to serialize anything manually, as long as you've provided a model class in C#.
Json.NET is quite smart and serializes your parameters automagically.
[HttpPost]
public HttpResponseMessage QuestionnaireSubmit(AttributeValueTB form)
{
// Form is serialized and can be used here
}
If you'd like to read the cookies too, you could use Request.Cookies in this method.
you need to collect information from 'jsoncontent' not from 'form'
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
entityclass obj= JsonConvert.DeserializeObject<entityclass>(jsonContent);
and if you using class object as parameter also work with your context, need to change the method as put like this.
[HttpPut]
public HttpResponseMessage Put(int id)
{
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
entityclass obj= JsonConvert.DeserializeObject<entityclass>(jsonContent);
...
}

Infragistics IgniteUI Tree Load OnDemand

I am using the plugin http://www.igniteui.com/tree/overview and want to load the tree data on demand.
My declaration of the tree is :
$("#tree").igTree({
checkboxMode: "off",
singleBranchExpand: true,
loadOnDemand: true,
dataSourceUrl : "/home/getagreements",
nodeClick: function (evt, ui) {
},
dataSourceType: "json",
initialExpandDepth: -1,
pathSeparator: ".",
bindings: {
textKey: "Text",
valueKey: "Value",
imageUrlKey: "ImageUrl",
childDataProperty: "Value",
Description: "Description"
},
},
dragAndDrop: false,
nodeExpanding: function (evt, ui) {
}
});
and the JSON output for home/getagreements is
return Json(agrmnts, JsonRequestBehavior.AllowGet);
where
List<Agreements> agrmnts = new List<Agreements>();
and the class definitions as below:
[JsonObject(MemberSerialization = Newtonsoft.Json.MemberSerialization.OptIn)]
public class AgreementNode
{
[JsonProperty(Order = 1)]
public string AgreementNbr { get; set; }
[JsonProperty(Order = 2)]
public string ExternalDescription { get; set; }
[JsonProperty(Order = 3)]
public string Description { get; set; }
[JsonProperty(Order = 4)]
public string EffDate { get; set; }
[JsonProperty(Order = 5)]
public string ExpDate { get; set; }
[JsonProperty(Order = 6)]
public string ReleaseStatus { get; set; }
[JsonProperty(Order = 7)]
public string ImageUrl { get; set; }
[JsonProperty(Order = 8)]
public string Folder { get; set; }
[JsonProperty(Order = 9)]
public string Value { get; set; }
[JsonProperty(Order = 10)]
public string Text { get; set; }
}
public class Agreements
{
public string AgreementType { get; set; }
public string Text { get; set; }
public string Value { get; set; }
public string Folder { get; set; }
public string ImageUrl { get; set; }
public List<AgreementNode> agreements { get; set; }
}
The first level data is displayed correct but when I click the node the same data is binding again. Please suggest if I am missing any configuration settings for Loading on Demand
With the current configuration the igTree is using the dataSourceUrl to request the new data from the same controller action you used to bind the initial level. At this point you would need to use the parameters the tree is providing to the controller action - path, binding and depth - to return the correct layer of data.
Here's an example of how you can do this.

angularjs post data to mvc controller in json format

I am working on a project in which I have used angularjs and mvc.I am passing data from angular js controller to my mvc controller by $http.post().For now I am using frombody attribute to retreive data like this -public string GetIssueDescription([FromBody]dynamic issueId).But I want that if I could do like this
public string GetIssueDescription(int issueId)
angularjs controller code
//show issue details
$scope.showIssueDetails = function (issue) {
//$scope.issueCount = 2;
$scope.issueDetailsLoaded = false;
$scope.selectedIssue = issue;
$scope.statusName = issue.StatusName;
var issueId = issue.Id;
var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/GetIssueDescription/';
$http.post(url, JSON.stringify({ issueId: issueId })).success(function (data, status, headers, config) {
if (data != '' || data.length >= 0) {
$scope.selectedIssue.Description = $sce.trustAsHtml(angular.fromJson(data));
$scope.selectedIssue = issue;
$scope.showedit = true;
$scope.showeditdesc = true;
//setting default properties
//$scope.issue.DueDate = $scope.selectedIssue.DueDate;
$scope.getIssueComment($scope.selectedIssue);
$scope.issueDetailsLoaded = true;
}
else if (data == '') {
$scope.selectedIssue.Description = "";
} else {
$scope.errors.push(data.error);
}
});
if($scope.isVisible==false) {
$("#changedetailsbox").hide();
$scope.isVisible = true;
}
if ($scope.isVisibleReply == false) {
$("#postReplybox").hide();
$scope.isVisibleReply = true;
}
};
MVC controller code
[HttpPost]
[AuthenticationRequired]
public string GetIssueDescription([FromBody]dynamic issueId)
{
try
{
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(issueId.ToString());
var selectedIssueId = new Guid(dictionary["issueId"]);
var result = PublicLayer.GetIssueDescription(selectedIssueId);
return result.IsSuccessful ? result.Result : string.Empty;
}
catch (Exception ex)
{
BLL.Base.BaseLayer.WriteApplicationLog(ex);
return string.Empty;
}
}
Please suggest how I could directly use my json data in my mvc controller.I took reference of this post but it didn't worked for me-Code I referred
I already have an issue model
public partial class Issue
{
public Guid Id { get; set; }
public Guid ProjectId { get; set; }
public Guid CreatorUserId { get; set; }
public Guid AssignedUserId { get; set; }
public Guid OwnerUserId { get; set; }
public Guid LastUpdatedUserId { get; set; }
public int DisplayId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int IssueStatusId { get; set; }
public int IssuePriorityId { get; set; }
public int IssueTypeId { get; set; }
public int IssueCategoryId { get; set; }
public Guid? AffectedMilestoneId { get; set; }
public int IssueResolutionId { get; set; }
public DateTime DueDate { get; set; }
public Guid? MilestoneId { get; set; }
public decimal Estimation { get; set; }
public int Progress { get; set; }
public string SenderEmailAddress { get; set; }
public bool IsDeleted { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime LastUpdatedOn { get; set; }
}
Please suggest is it possible to use my this class in my method-public string GetIssueDescription(Issue issue) like this and can retreive my id by using issue.Id.Please suggest how to achieve this.
In your controller
change
public string GetIssueDescription([FromBody]dynamic issueId)
to
public string GetIssueDescription(Issue issue)
in your angular POST
var issueId = issue.Id;
.
.
$http.post(url, { Id: issueId }).success(function (data, status, headers, config) {

Categories