简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM