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!
Related
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
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.
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.
I'm still new to mvc5 and had very little knowledge with javascript. I know that my cascading works but I'm having trouble with the display part. What I want to do is have 2 dropdown list. 1 containing all customer names and the 2nd will have a list of their pending transactions. Basically 1st dropdown will have customer names while the 2nd will have video titles. Please check my code where I did wrong. Why I can't display the video titles. BTW I tried other properties in my transactions and I can display them. That's how I know that my cascading is not the problem.
Models
//Transaction Model
TransactionID { get; set; }
public int CustomerID { get; set; }
public virtual Customers CustomerName { get; set; }
public int VideoID { get; set; }
public virtual Videos Videos { get; set; }
public int Quantity { get; set; }
[ReadOnly(true)]
public DateTime? TransactionDate { get; set; }
[ReadOnly(true)]
public DateTime? DueDate { get; set; }
[ReadOnly(true)]
public Decimal Cost { get; set; }
[ReadOnly(true)]
public String ReturnStatus { get; set;}
//Customers Model
public int CustomerID { get; set; }
public string CustomerName { get; set; }
public string CustomerAddress { get; set; }
public string CustomerContact { get; set; }
//Video Model
public int VideoID { get; set; }
public string VideoTitle { get; set; }
public int CategoryID { get; set; }
public virtual Category VideoCategory { get; set; }
[Range(0,99)]
public int VideoIn { get; set; }
[Range(0,99)]
public int VideoOut { get; set; }
Conroller
public ActionResult CustomerList()
{
var customers = db.Customers.OrderBy(x => x.CustomerID).ToList();
if (HttpContext.Request.IsAjaxRequest())
{
return Json(new SelectList(
customers,
"CustomerID",
"CustomerName"), JsonRequestBehavior.AllowGet
);
}
return View(customers);
}
public ActionResult Transact(int cusId)
{
var transact = db.Transactions
.Where(x => x.CustomerID == cusId)
.Where(s => s.ReturnStatus == "FALSE").ToList();
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
transact,
"TransactionID",
"VideoTitle"), JsonRequestBehavior.AllowGet
);
return View(transact);
}
I figure out a solution after hours of trial an error. What I did is I added a join in my query.
var transact = db.Transactions
.Where(x => x.CustomerID == cusId)
.Where(s => s.ReturnStatus == "FALSE")
.Join(db.Videos,
v => v.VideoID,
t => t.VideoID,
(transaction, videos) => new {
TransactionID = transaction.TransactionID,
VideoTitle = videos.VideoTitle }).ToList();
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; }
}