Parameter from angular not mapped into C# object - javascript

I have a problem with mapping one parameter from my angular $http call to C# method.
On a server side I use MVC. On a client is angular. I've tried to debug with developer tools inside Chrome and everything was fine, without errors.
Parameter which doesn't map (stays null) is cORAM_NTO. I've checked in console that $scope.Note is filled with value.
But, on the server side value for cORAM_NTO is null.
Here is call on client side (angular):
$scope.SaveModal = function (event)
{
$http(
{
method: "POST",
url: $scope.UrlSaveDataCAORAM,
data:
{
iORAM_KEY: $scope.CurrentORAM_KEY,
dORAM_DSE: $scope.SellDate,
cORAM_MPA: $scope.WayPayment,
cORAM_NIC: $scope.ConfirmationNumber,
cORAM_ANB: $scope.AccountNumber,
dORAM_DBE: $scope.DateUse,
decORAM_VAU: $scope.AmountUse,
cORAM_ANB2: $scope.AccountAmountUseRest,
dORAM_DBE2: $scope.DateUseRest,
decORAM_VAU2: $scope.AmountUseRest,
cORAM_NTO: $scope.Note
}
}).then(function success(response)
{
}, function failure()
{
})
}
Here is class for DTO_CAORAM (parameter cORAM_NTO is last):
public class DTO_CAORAM
{
public int? iORAM_KEY { get; set; }
public int? iORAS_KEY { get; set; }
public int? iMEST_KEY { get; set; }
public int? iUNIT_KEY { get; set; }
public string cORAM_SRT { get; set; }
public string cORAM_STA { get; set; }
public DateTime? dORAM_DAT { get; set; }
public double? decORAM_QUA { get; set; }
public string cORAM_UNI { get; set; }
public double? decORAM_NET { get; set; }
public double? decORAM_GRO { get; set; }
public DateTime? dORAM_DSE { get; set; }
public string cORAM_MPA { get; set; }
public string cORAM_NIC { get; set; }
public string cORAM_ANB { get; set; }
public DateTime? dORAM_DBE { get; set; }
public double? decORAM_VAU { get; set; }
public string cORAM_ANB2 { get; set; }
public DateTime? dORAM_DBE2 { get; set; }
public double? decORAM_VAU2 { get; set; }
public string cMEST_CDO2 { get; set; }
public int? iMERC_KEY { get; set; }
public int? iACCO_KEY { get; set; }
public int? iORAC_KEY { get; set; }
public string cORAM_NTO { get; set; }
}
And finally function on server side (all params are mapped except cORAM_NTO):
public void SaveDataCAORAM(DTO_CAORAM dto)
{
}
Here is POST request recorded from a network tab:
dto
:
{iORAM_KEY: "160000008", dORAM_DSE: "01.06.2016", cORAM_MPA: "fsfsfsdf", cORAM_NIC: "6666",…}
cORAM_ANB
:
"jjjgfhgfhg"
cORAM_ANB2
:
"rtttttt"
cORAM_MPA
:
"fsfsfsdf"
cORAM_NIC
:
"6666"
cORAM_NTO
:
"notest test"
dORAM_DBE
:
"02.07.2016"
dORAM_DBE2
:
"03.08.2016"
dORAM_DSE
:
"01.06.2016"
decORAM_VAU
:
"54444,0000"
decORAM_VAU2
:
"7777,0000"
iORAM_KEY
:
"160000008"

I've renamed parameter cORAM_NTO to cORAM_NTO1 and tried that. It worked. Than I renamed it back and it worked with cORAM_NTO.

Related

Filter Not Filtering Records

I'm trying to find records in $scope.employeesthat do not have a matching record in $scope.allEmployeeGroups, but the filter is not Filtering records, even though I know for sure that there should only be a few unmatched, it returns all of the records. For each record, the indexOf == -1 when I know that it should not. I can't figure out what I am doing wrong. Here is my code:
function getNonGroupEmployees() {
var arr = $scope.employees.filter(function (item) {
return $scope.allEmployeeGroups.indexOf(item.EmployeeId) === -1;
})
return arr;
}
Employee Object:
public System.Guid EmployeeId { get; set; }
public Nullable<System.Guid> SiteId { get; set; }
public string SiteName { get; set; }
public string DisplayName { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Suffix { get; set; }
public string Alias { get; set; }
public Nullable<System.DateTime> DOB { get; set; }
public string SsnLastFour { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public bool IsActive { get; set; }
public bool IsLoginEnabled { get; set; }
public Nullable<System.DateTime> LastLogin { get; set; }
public Nullable<System.Guid> SignatureTypeId { get; set; }
public string SignatureType { get; set; }
public string NumberHome { get; set; }
public string NumberCell { get; set; }
public bool IsSuperUser { get; set; }
public bool IsDeleted { get; set; }
public System.DateTime Created { get; set; }
public System.DateTime LastModified { get; set; }
public Nullable<System.Guid> ModifiedByEmployeeId { get; set; }
public string ApiKey { get; set; }
Group Object:
public Guid EmployeeGroupId { get; set; }
public Guid SiteId { get; set; }
public Guid EmployeeId { get; set; }
public Guid SiteGroupId { get; set; }
public bool IsDeleted { get; set; }
public DateTime Created { get; set; }
public DateTime LastModified { get; set; }
public Guid? ModifiedByEmployeeId { get; set; }
public string SiteName { get; set; }
public string EmployeeName { get; set; }
public string SiteGroupName { get; set; }
public string ModifiedByEmployeeName { get; set; }
Any assistance is greatly appreciated.
Instead of searching object with .IndexOf(), use property matching. Object will not match if two objects do not have same reference.
Try with following code block:
function getNonGroupEmployees() {
var arr = $scope.employees.filter(function (item) {
return $scope.allEmployeeGroups.find(function(p){
return p.EmployeeId == item.EmployeeId
})=== null;
})
return arr;
}
AS requested here are data structures:
Employee:
public System.Guid EmployeeId { get; set; }
public Nullable<System.Guid> SiteId { get; set; }
public string SiteName { get; set; }
public string DisplayName { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Suffix { get; set; }
public string Alias { get; set; }
public Nullable<System.DateTime> DOB { get; set; }
public string SsnLastFour { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public bool IsActive { get; set; }
public bool IsLoginEnabled { get; set; }
public Nullable<System.DateTime> LastLogin { get; set; }
public Nullable<System.Guid> SignatureTypeId { get; set; }
public string SignatureType { get; set; }
public string NumberHome { get; set; }
public string NumberCell { get; set; }
public bool IsSuperUser { get; set; }
public bool IsDeleted { get; set; }
public System.DateTime Created { get; set; }
public System.DateTime LastModified { get; set; }
public Nullable<System.Guid> ModifiedByEmployeeId { get; set; }
public string ApiKey { get; set; }
Employee Group
public Guid EmployeeGroupId { get; set; }
public Guid SiteId { get; set; }
public Guid EmployeeId { get; set; }
public Guid SiteGroupId { get; set; }
public bool IsDeleted { get; set; }
public DateTime Created { get; set; }
public DateTime LastModified { get; set; }
public Guid? ModifiedByEmployeeId { get; set; }
public string SiteName { get; set; }
public string EmployeeName { get; set; }
public string SiteGroupName { get; set; }
public string ModifiedByEmployeeName { get; set; }
Thanks to answer found Here, here is what eventually worked:
function getNonGroupEmployees() {
var result = $scope.employees.filter(function (o1) {
return !$scope.allEmployeeGroups.some(function (o2) {
return o1.EmployeeId === o2.EmployeeId; // assumes unique id
});
})
return result;
}

Javascript ajax passing dynamically created json object to a web service

I have a web service function that has an object parameter,
Function from controller
public string Post([FromBody]LoanApplication value)
{
LoanApplicationDAO appDAO = new LoanApplicationDAO();
string res = "";
res = appDAO.ReleaseLoanApplication(value);
if (res == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}
return res;
}
LoanApplication contains
public class LoanApplication
{
public string AccountAddress { get; set; }
public string AccountName { get; set; }
public string AccountNumber { get; set; }
public string AccountTag { get; set; }
public string ApplicationNumber { get; set; }
public string ApplicationType { get; set; }
public string Approver { get; set; }
public string BSPTagging { get; set; }
public string BuyOutAmount { get; set; }
public string CIFKey { get; set; }
public string ClassificationEconomicActivity { get; set; }
public string ClassificationSizeOfFirm { get; set; }
public string CoMaker1 { get; set; }
public string CoMaker2 { get; set; }
public string CoMakerName1 { get; set; }
public string CoMakerName2 { get; set; }
public string CreditLimit { get; set; }
public string DateGranted { get; set; }
public string DepEdDivision { get; set; }
public string DepEdEmployeeID { get; set; }
public string DepEdRegion { get; set; }
public string DepEdStation { get; set; }
public string Disbursement { get; set; }
public string DocStamps { get; set; }
public string DOSRIField { get; set; }
public string EmailAddress { get; set; }
public string FirstPaymentDate { get; set; }
public string GroupCode { get; set; }
public string GroupName { get; set; }
public string Insurance { get; set; }
public string InterestRate { get; set; }
public string KnockedOffAccountNumber { get; set; }
public string KnockedOffAmount { get; set; }
public string LandlineNumber { get; set; }
public string LoanAmount { get; set; }
public string LPOCode { get; set; }
public string Maker { get; set; }
public string MaturityDate { get; set; }
public string MobileNumber { get; set; }
public string MonthlyAmort { get; set; }
public string MothersMaidenName { get; set; }
public string NDaysDiscount { get; set; }
public string NoOfInstall { get; set; }
public string PaymentFrequency { get; set; }
public string PayOutMode { get; set; }
public string PEPTagging { get; set; }
public string Product { get; set; }
public string Purpose { get; set; }
public string Security { get; set; }
public string ServiceFees { get; set; }
public string SourceOfPayment { get; set; }
public string SpouseMobileNumber { get; set; }
public string SpouseName { get; set; }
public string Term { get; set; }
public string AOUserID { get; set; }
public string AOName { get; set; }
public string LSOCode { get; set; }
public string IsBranch { get; set; }
}
When I use the debugging mode from VS 2012 the LoanObj accountname and accountnumer is null, but when i check my pass value from ajax it has value, checked it from google chromes console
sample format of the value from ajax jsonObj: { AccountName:"test name", AccountAddress: "test address", etc.. }
my ajax function
$('body').on('click', '#btnSubmit', function () {
var jsonObj = {};
$('#lfs_form tbody input[type="text"]').each(function () {
jsonObj[this.id] = this.value;
});
var req2 =
$.ajax({
type: 'post',
url: '../lfsapi/loanapplication/',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({
jsonObj
//AccountAddress: jsonObj['AccountAddress']
})
});
req.error(function (request, status, error) {
alert(request.responseJSON['Message']);
});
req.done(function (data) {
});
});
But when I try
data: JSON.stringify({
AccountName: jsonObj['AccountName'],
AccountNumber: jsonObj['AccountNumber']
})
It works, and successfully pass the expected values to function, my sample only is 2 objects but in my real code i have more than 40 objects thats why i tried using loop..anyone knows how can i fix the issue?
thank you
Additional code, to populate my form
$.ajax({
type: 'get',
url: '../lfsapi/loanapplication/',
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
req.error(function (request, status, error) {
alert(request.responseJSON['Message']);
});
req.done(function (data) {
var toappend = '';
$.each(data, function (key, val) {
toappend += '<tr>';
toappend += '<td>' + val + '</td><td><input style="width:500px;" type="text" id=' + val + ' /></td>';
toappend += '</tr>';
});
toappend += '<tr><td align="right" colspan="2"><button id="btnSubmit" type="button">Submit</button></td></tr>';
$('#lfs_form tbody').append(toappend);
});
There are several mistakes I noticed in your code :
firstly you are using jsonObj[this.id] for assigning value to object
members. so this.id should be AccountName or AccountNumber else it
would not assign value to required members.
secondly, remove extra brakets {} from JSON.stringify and use like this
JSON.stringify(
jsonObj
);
Solve the issue by
data: JSON.stringify(jsonObject)
thank you all

Service Return Empty Lists To Api Controller

I am working in service fabrics micro services , where i need to fetch record for an object. when I send request to API , it shows me empty lists while rest of the data is in place. while debugging I came to know that before returning to API controller my service object has all the data expected i.e lists has data , but when it comes back to web API the lists are empty.
After searching for solution over web I came to know that every time a request is to the API the lists are recreated , so it shows empty result. Any Solutions to come out of this problem?
Here is my piece of code.
The following Is the Web Api Method.
[HttpGet()]
[Route("edit/{readingListId}")]
[ProducesResponseType(typeof(List<GetReadingListDTO>), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(List<GetReadingListDTO>), (int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetReadingListById(int readingListId)
{
try
{
var readingList = await this._readingListService.GetReadingListByIdAsync(readingListId);
return Ok(readingList);
}
catch (Exception ex)
{
this._logger.LogError(ex.Message);
return BadRequest();
}
}
The following Is the Service Method.
public async Task<Domain.ReadingList> GetReadingListByIdAsync(int readingListId)
{
try
{
Domain.ReadingList readingList = await _repository.FindById(readingListId);
return readingList;
}
catch (Exception ex)
{
throw;
}
}
Moreover , This Is My Entity.
public class ReadingList : EntityBase, IAggregateRoot, IAggregateCreateRoot, IAggergateUpdateRoot, IAggregateDeleteRoot
{
public ReadingList()
{
this.Items = new List<ReadingListItem>();
this.Assignees = new List<ReadingListAssignee>();
}
public int Id { get; set; }
public EntityType EntityTypeId { get; set; }
public int EntityId { get; set; }
public string Title { get; set; }
public DateTime CompletionDate { get; set; }
public int ReminderDay { get; set; }
public string ReminderDayType { get; set; }
public bool SendReminder { get; set; }
public int CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public int? UpdatedBy { get; set; }
public DateTime? UpdatedDate { get; set; }
public int? DeletedBy { get; set; }
public DateTime? DeletedDate { get; set; }
public bool? Deleted { get; set; }
public List<ReadingListItem> Items { get; private set; }
public List<ReadingListAssignee> Assignees { get; private set; }
}
Thanks!
Edited
The Issue Was Resolved , By Simply Changing The dll Versions.One Of The Service Had And Old Version While The Version Was Updated In The Other One.
Thanks For The Help.

Mapping plugin taking too long to update model

I am using KO 3.2 and I am experiencing a weird issue when using the mapper plugin.
I use the following code to get some json data and update my model.
self.load = function (item, event) {
var d = { expedienteId: self.Id(), id: item.Id() };
$.ajax({
type: "POST",
url: "/Expediente/Evolucion/",
data: JSON.stringify(d),
contentType: "application/json; charset=utf-8",
cache: false,
dataType: "json"
})
.success(function (data) {
ko.mapping.fromJS(data.Data, {}, self.Evolucion);
})
};
The data return is:
{"Success":true,"Message":null,"Data":{"Id":1,"ExpedienteId":0,"Fecha":"\/Date(1443304800000)\/","Medico"
:"Gabriel R Lopez Gutierrez","ImagenDescriptiva":null,"Sintoma":"Sintomas","Objetivo":"Objetivo","Diagnostico"
:"Diagnostico 1","Analisis":"Analisis","Observaciones":"Oservaciones","CieCode":"Y55.5","CieDescription"
:"Efectos adversos de drogas contra el resfriado común","Tratamiento":"Tratamiento","Pronostico":"Pronostico"
,"Anotaciones":"Anotaciones","RequiereCirugia":true,"Descripcion":null,"TensionArterial":0.00000,"FrecuenciaCardiaca"
:0.00000,"FrecuenciaRespiratoria":0.00000,"Temperatura":0.00000,"HabitusExterior":"habitus exterior"
,"Peso":65.00000,"Talla":2.39000,"IndiceMasaCorporal":0.00000,"PerimetroCefalico":69.90000,"SuperficieCorporal"
:1.99000,"SegmentoSuperior":2.39000,"SegmentoInferior":2.39000,"ExtremidadInferior":1.49000,"PerimetroAbdominal"
:1.99000,"PerimetroBraquial":0.89000,"PerimetroAnterobraquial":0.89000,"PerimetroToracico":5.99000,"PerimetroSural"
:1.79000,"PerimetroCrural":0.00000,"Braza":0.00000,"Brazada":2.39000},"Errors":null}
I have 2 problems with this code. 1) The first one is that I need to use ko.mapping.fromJS - ko.mapping.fromJS(data.Data, {}, self.Evolucion). For some reason, whenever I use ko.mapping.fromJSON, my model won't get populated. It is worth mentioning that I do use fromJSON in other parts of the application and it works fine.
2) The second problem is: Since fromJSON doesn't work, I am using fromJS which for some reason works even though I passing a json string to it. In any case, although fromJS does work, it takes about 25 seconds to map the data to my model. When processing this line, my browser freezes, i get the Firefox is not responding message and after 25 seconds it comes back and my model is populated correctly.
Any ideas how can I fix this? Either fix it so that I can use fromJSON or if fix it so that fromJS doesn't hang and take so long to do the mapping?
Any help is greatly appreciated.
Thanks!
UPDATE
Here is the model for Evolucion (C#):
public class Evolucion
{
public int Id { get; set; }
public int ExpedienteId { get; set; }
public DateTime Fecha { get; set; }
public string Medico { get; set; }
public string ImagenDescriptiva { get; set; }
public string Sintoma { get; set; }
public string Objetivo { get; set; }
public string Diagnostico { get; set; }
public string Analisis { get; set; }
public string Observaciones { get; set; }
public string CieCode { get; set; }
public string CieDescription { get; set; }
public string Tratamiento { get; set; }
public string Pronostico { get; set; }
public string Anotaciones { get; set; }
public bool RequiereCirugia { get; set; }
public string Descripcion { get; set; }
public decimal TensionArterial { get; set; }
public decimal FrecuenciaCardiaca { get; set; }
public decimal FrecuenciaRespiratoria { get; set; }
public decimal Temperatura { get; set; }
public string HabitusExterior { get; set; }
public decimal Peso { get; set; }
public decimal Talla { get; set; }
public decimal IndiceMasaCorporal { get; set; }
public decimal PerimetroCefalico { get; set; }
public decimal SuperficieCorporal { get; set; }
public decimal SegmentoSuperior { get; set; }
public decimal SegmentoInferior { get; set; }
public decimal ExtremidadInferior { get; set; }
public decimal PerimetroAbdominal { get; set; }
public decimal PerimetroBraquial { get; set; }
public decimal PerimetroAnterobraquial { get; set; }
public decimal PerimetroToracico { get; set; }
public decimal PerimetroSural { get; set; }
public decimal PerimetroCrural { get; set; }
public decimal Braza { get; set; }
public decimal Brazada { get; set; }
}
Thanks for the help. It turned out that a very large array properties where being mapped (and shouldn't have) and when refreshing the model with either .fromJS or .fromJSON it was causing the UI to choke.
After ignoring the properties during the mapping ('ignore': [Properties]) the problem when away.
Thanks again for the help!

how to send json data to serializable class

there is a problem when send json data to serializable class. On client side when i check data on browser it is true but on server side the fields of serializable class are null.
Client side (using dojo) : on the debugger line fileds of ticket object are assigned
var Ticket = {
ProductId: productId,
Type: ticketType
};
DataService.xhrPageMethodJson("api/Tickets/MyTickets"
, dojo.toJson(Ticket)
, {
success: function (data) {
debugger
loadSubPage(getRoot("Support/Tickets.aspx?mode=list"));
},
error: function (err) {
LoadingOverlay.hide();
}
});
Web Method: On this method ticket.ProductId, ticket.Type fields has default value or null.
[HttpPost]
[AcceptVerbs("POST")]
[ActionName("MyTickets")]
[Authorize]
public void MyTickets([FromBody]Ticket ticket)
{
DataTable myTickets = db.Tickets.MyTickets(Globals.LogonUser.User.Id, ticket.ProductId, ticket.Type);
WebContext.Session["Tickets"] = myTickets;
}
Ticket class:
[Serializable]
[EntityTable(Name = "Tickets")]
public class Ticket : Entity
{
public override int Id { get; set; }
public string Subject { get; set; }
public string Message { get; set; }
public DateTime SentDate { get; set; }
[JoinField(typeof(User), "Id")]
public int SenderUserId { get; set; }
[JoinField(typeof(Product), "Id")]
public int ProductId { get; set; }
[JoinField(typeof(TicketImportanceLevel), "Id")]
public int ImportanceLevel { get; set; }
public int Analyze { get; set; }
public int SolutionTransactionId { get; set; }
[JoinField(typeof(TicketType), "Id")]
public int Type { get; set; }
public int Status { get; set; }
public int AssignedUserId { get; set; }
public float Score { get; set; }
}
I have solved this problem with marking properties as data member and class as data contract. Here I am sharing new class structure:
[Serializable]
[DataContract]
[EntityTable(Name = "Tickets")]
public class Ticket : Entity
{
[DataMember]
public override int Id { get; set; }
[DataMember]
public string Subject { get; set; }
[DataMember]
public string Message { get; set; }
[DataMember]
public DateTime SentDate { get; set; }
[JoinField(typeof(User), "Id")]
[DataMember]
public int SenderUserId { get; set; }
[JoinField(typeof(Product), "Id")]
[DataMember]
public int ProductId { get; set; }
[JoinField(typeof(TicketImportanceLevel), "Id")]
[DataMember]
public int ImportanceLevel { get; set; }
[DataMember]
public int Analyze { get; set; }
[DataMember]
public int SolutionTransactionId { get; set; }
[JoinField(typeof(TicketType), "Id")]
[DataMember]
public int Type { get; set; }
[DataMember]
public int Status { get; set; }
[DataMember]
public int AssignedUserId { get; set; }
[DataMember]
public float Score { get; set; }
}

Categories

Resources