Javascript ajax passing dynamically created json object to a web service - javascript

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

Related

How do i do crud from multiple tables in visual studio mvc

Hi new to visual studio and mvc in general and im trying to make a mvc crud including two tables. I have so far managed to do Create and List in index but i have having problem trying to edit,delete and show details.
Desc Class
[Table("klsm_InvoiceDesc")]
public class Desc
{
[Key]
public string InternalInvoiceNo { get; set; }
public string InvoiceNo { get; set; }
public int DescNo { get; set; }
public string Principal { get; set; }
public string ChargeCode { get; set; }
public string Quantity { get; set; }
public string Description { get; set; }
public string UnitPrice { get; set; }
public string Amount { get; set; }
public string ForeignAmount { get; set; }
public string EL1 { get; set; }
public string EL2 { get; set; }
public string ShortName { get; set; }
public string InvoiceType { get; set; }
public string PONumber { get; set; }
public string Batch { get; set; }
public string CCVBatch { get; set; }
public string PaidAmount { get; set; }
public string Paid { get; set; }
public string TT { get; set; }
public string BankCode { get; set; }
}
College Class
[Table("klsm_Invoice")]
public class College
{
[Key]
public string InternalInvoiceNo { get; set; }
public string InvoiceNo { get; set; }
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime InvoiceDate { get; set; }
public string CustomerName { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public decimal Amount { get; set; }
public decimal ForeignAmount { get; set; }
public string UserCreated { get; set; }
public string UserModified { get; set; }
public int AccMonth { get; set; }
public int AccYear { get; set; }
public string AccStatus { get; set; }
public string Status { get; set; }
public string PaidStatus { get; set; }
public string Principal { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
public string EL1 { get; set; }
public string InvoiceType { get; set; }
public string CurrencyType { get; set; }
public decimal ExchangeRate { get; set; }
public string GSTChecked { get; set; }
public DateTime PaymentSchedule { get; set; }
public string PaymentMode { get; set; }
public string CashAdvance { get; set; }
}
my home controller
public class HomeController : Controller
{
// GET: Home
DataContext db = new DataContext();
public ActionResult Index()
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice").ToList();
return View(data);
//List<College> klsm_Invoice = db.klsm_Invoice.ToList();
//return View(klsm_Invoice);
}
// GET: Home/Details/5
public ActionResult Details(string id)
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice WHERE InternalInvoiceNo=#p0", id).SingleOrDefault();
return View(data);
}
// GET: Home/Edit/5
public ActionResult Edit(string id)
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice WHERE InternalInvoiceNo=#p0", id).SingleOrDefault();
return View(data);
}
// POST: Home/Edit/5
[HttpPost]
public ActionResult Edit(string id, College collection)
{
db.Entry(collection).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
// GET: Home/Delete/5
public ActionResult Delete(string id)
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice WHERE InternalInvoiceNo=#p0", id).SingleOrDefault();
return View(data);
}
// POST: Home/Delete/5
[HttpPost]
public ActionResult Delete(string id, College collection)
{
try
{
// TODO: Add delete logic here
int result = db.Database.ExecuteSqlCommand("DELETE FROM klsm_Invoice WHERE InternalInvoiceNo=#p0", id);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public ActionResult Search(string InternalInvoiceNo)
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice WHERE InternalInvoiceNo = '" + InternalInvoiceNo + "' ").ToList();
return PartialView("DefaultIndex", data);
}
// GET: Home/Create
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult CreateInvoice(string invoiceDetailsList, string internalInvoiceNo, string invoiceNo, DateTime invoiceDate, string customerName, int year, int month, string amount, string foreignAmount, string userCreated, string userModified, int accMonth, int accYear, string accStatus, string status, string paidStatus, string principal, DateTime dateCreated, DateTime dateModified, string el1, string invoiceType, string currrencyType, string exchangeRate, string gstChecked, DateTime paymentSchedule, string paymentMode, string cashAdvance)
{
List<Desc> detailsList = JsonConvert.DeserializeObject<List<Desc>>(invoiceDetailsList);
var addingmaster = new College();
{
addingmaster.InternalInvoiceNo = internalInvoiceNo;
addingmaster.InvoiceNo = invoiceNo;
addingmaster.InvoiceDate = Convert.ToDateTime(invoiceDate);
addingmaster.CustomerName = customerName;
addingmaster.Year = year;
addingmaster.Month = month;
addingmaster.Amount = Convert.ToDecimal(amount);
addingmaster.ForeignAmount = Convert.ToDecimal(foreignAmount);
addingmaster.UserCreated = userCreated;
addingmaster.UserModified = userModified;
addingmaster.AccMonth = accMonth;
addingmaster.AccYear = accYear;
addingmaster.AccStatus = accStatus;
addingmaster.Status = status;
addingmaster.PaidStatus = paidStatus;
addingmaster.Principal = principal;
addingmaster.DateCreated = Convert.ToDateTime(dateCreated);
addingmaster.DateModified = Convert.ToDateTime(dateModified);
addingmaster.EL1 = el1;
addingmaster.InvoiceType = invoiceType;
addingmaster.CurrencyType = currrencyType;
addingmaster.ExchangeRate = Convert.ToDecimal(exchangeRate);
addingmaster.GSTChecked = gstChecked;
addingmaster.PaymentSchedule = Convert.ToDateTime(paymentSchedule);
addingmaster.PaymentMode = paymentMode;
addingmaster.CashAdvance = cashAdvance;
db.klsm_Invoice.Add(addingmaster);
db.SaveChanges();
}
foreach (var item in detailsList)
{
Desc addingdetails = new Desc();
addingdetails.InternalInvoiceNo = item.InternalInvoiceNo;
addingdetails.InvoiceNo = item.InvoiceNo;
addingdetails.DescNo = item.DescNo;
addingdetails.Principal = item.Principal;
addingdetails.ChargeCode = item.ChargeCode;
addingdetails.Quantity = item.Quantity;
addingdetails.Description = item.Description;
addingdetails.UnitPrice = item.UnitPrice;
addingdetails.Amount = item.Amount;
addingdetails.ForeignAmount = item.ForeignAmount;
addingdetails.EL1 = item.EL1;
addingdetails.EL2 = item.EL2;
addingdetails.ShortName = item.ShortName;
addingdetails.InvoiceType = item.InvoiceType;
addingdetails.PONumber = item.PONumber;
addingdetails.Batch = item.Batch;
addingdetails.CCVBatch = item.CCVBatch;
addingdetails.PaidAmount = item.PaidAmount;
addingdetails.Paid = item.Paid;
addingdetails.TT = item.TT;
addingdetails.BankCode = item.BankCode;
//addingdetails.Id = item.Id;
db.klsm_InvoiceDesc.Add(addingdetails);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
}
I have yet to add views for the needed help so anything will help rn

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;
}

Parameter from angular not mapped into C# object

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.

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