My web api input [FormBody] is getting null. why ?

mehmood tekfirst 771 Reputation points
2022-07-01T14:14:17.947+00:00

Hi,

My web api input [FormBody] is getting null. why ?

These are models

 public class YourBookingVM  
    {  
        public bool? IsEnquiry { get; set; }  
  
        public HomeSearch? HomeSearch { get; set; }  
  
        public CarDetails? CarDetails { get; set; }  
  
        public string? CurrentCarDetails { get; set; }   
  
        public List<Extras>? Extras { get; set; }  
  
        public string? CurrentExtras { get; set; }  
        public ShortPaymentDetails? PaymentDetails { get; set; }          
  
       
        public CreateEnquiryViewModel? Enquiry { get; set; }  
  
        public string? EnquiryCode { get; set; }  
  
        public string? LegalEntity { get; set; }  
        public string? CoRegNumber { get; set; }  
        public string? RegOffice { get; set; }  
        public decimal? BkWebWeekendSurcharge { get; set; }  
    }  

 

public class HomeSearch  
    {  
        public string? PostCode { get; set; }  
        public string Branch { get; set; } = null!;  
        public int? BranchId { get; set; }  
  
        [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]  
        public DateTime StartDate { get; set; }  
  
        [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]  
        public DateTime EndDate { get; set; }  
  
        public TimeSpan StartTime { get; set; }  
        public TimeSpan EndTime { get; set; }  
        public string? VehicleType { get; set; }  
        public string? FuelType { get; set; }  
        public string? Transmission { get; set; }  
        public string? AirConditioning { get; set; }   
        public int? GroupId { get; set; }  
        public string? GroupName { get; set; }  
        public bool? IsNewSearch { get; set; }  
  
        public int? FleetId { get; set; }  
        public int? TariffId { get; set; }  
        public int? SpecialRateId { get; set; }  
        public int? VehicleCategoryId { get; set; }  
        public string? VehicleCategory { get; set; }  
        public bool? ChargeHalfDay { get; set; }  
  
        public double? ChargedDays { get; set; }  
  
        public string? PickupLocId { get; set; }  
        public int? FranchiseId { get; set; }  
        public int? SubofficeId { get; set; }  
  
        public bool? ApplyShortWeekend { get; set; }  
        public bool? ApplyLongWeekend { get; set; }  
  
        public double? BookingDays { get; set; }  
    }  

public class CarDetails  
    {  
        public int? Id { get; set; }  
        public string? Name { get; set; }  
        public decimal? Price { get; set; }  
        public string? PerDayPrice { get; set; }  
        public string? NoOfSeats { get; set; }  
        public string? AirBags { get; set; }  
        public string? NoOfDoors { get; set; }  
        public string? Gearbox { get; set; }  
        public string? FuelType { get; set; }  
        public string? VehicleType { get; set; }  
        public string? Transmission { get; set; }  
        public string? AirConditioning { get; set; }  
        public string? Group { get; set; }  
        public int? GroupId { get; set; }  
        public List<Extras>? Extras { get; set; }  
        public bool? IsAvailable { get; set; }  
        public string? DefaultImage { get; set; }  
        public List<FleetDTO>? GroupFleets { get; set; }  
        public int? PassengerSeats { get; set; }  
        public string? GroupIcon { get; set; }  
        public bool? IsSeasonExists { get; set; }  
    }  


 public class Extras  
    {  
        public int Id { get; set; }  
        public string? Name { get; set; }  
        public string? ClassName { get; set; }  
        public string? Icon { get; set; }  
        public string? NetPrice { get; set; }  
        public string? VatPercentage { get; set; }  
        public string? VatAmount { get; set; }  
        public string? PriceWithVatPerDay { get; set; }  
        public string? Total { get; set; }  
        public string? Quantity { get; set; }  
        public decimal Vat { get; set; }  
        public bool ChargePerDay { get; set; }  
    }  

public class ShortPaymentDetails  
    {  
        [Required(ErrorMessage = "Please Select Title", AllowEmptyStrings = true)]  
        public string? PTitle { get; set; }   
  
        [Required(ErrorMessage = "Please Enter First Name", AllowEmptyStrings = true)]  
        public string? PFirstName { get; set; }   
  
        [Required(ErrorMessage = "Please Enter Last Name", AllowEmptyStrings = true)]  
        public string PSurname { get; set; } = null!;  
        public string? PTelephone { get; set; }  
  
        [Required(ErrorMessage = "Please Enter Address", AllowEmptyStrings = true)]  
        public string? PAddress1 { get; set; }   
        public string? PAddress2 { get; set; }   
        public string? PAddress3 { get; set; }  
  
        [Required(ErrorMessage = "Please Select Town")]  
        public int PTown { get; set; }   
  
        [Required(ErrorMessage = "Please Select County")]  
        public int PCounty { get; set; }  
  
        public int PCountry { get; set; }  
  
        [Required(ErrorMessage = "Please Select Town", AllowEmptyStrings = true)]  
        public string? PTownNonUK { get; set; }  
  
        [Required(ErrorMessage = "Please Select County", AllowEmptyStrings = true)]  
        public string? PCountyNonUK { get; set; }  
        public string? PCountryName { get; set; }   
  
        [Required(ErrorMessage = "Please Enter Country")]  
        public int PCountryNonUK { get; set; }  
  
        [Required(ErrorMessage = "Please Enter Postcode", AllowEmptyStrings = true)]  
        public string? PZip { get; set; }  
        public bool PIsUkAddress { get; set; } = false;  
  
        [Required(ErrorMessage = "Please Enter Card Number", AllowEmptyStrings = true)]  
        //[Remote("Validation","Home",ErrorMessage = "Card number is not Valid")]  
        public string? CardNumber { get; set; }   
        public decimal Amount { get; set; } = 0;  
        public string? CurrencyCode { get; set; }  
  
        [Display(Name = "Payment Type:")]  
        [Required(ErrorMessage = "Please select the card type")]  
        public short CardType { get; set; } = 0;  
  
        public string? ValidFrom { get; set; }  
        [Required(ErrorMessage = "Please Enter Month & Year", AllowEmptyStrings = true)]  
        public string ExpiryMonth { get; set; } = null!;  
        [Required(ErrorMessage = " ", AllowEmptyStrings = true)]  
        public string ExpiryYear { get; set; } = null!;  
        public string IssueNo { get; set; } = null!;  
        [Required(ErrorMessage = "Please Enter Security Code", AllowEmptyStrings = true)]  
        public string? CVC { get; set; }   
        public string? Token { get; set; }  
        public string? ClientKey { get; set; }  
  
        //Drive Information  
  
        [StringLength(5, ErrorMessage = "Must be at least 6 Characters Long.", MinimumLength = 5)]  
        [Required(ErrorMessage = "Please Enter Code.", AllowEmptyStrings = true)]  
        public string? DCode { get; set; }  
  
        [Required(ErrorMessage = "Please Select Title", AllowEmptyStrings = true)]  
        public string? DTitle { get; set; }   
  
        [Required(ErrorMessage = "Please Enter First Name", AllowEmptyStrings = true)]  
        public string? DFirstName { get; set; }   
  
        [Required(ErrorMessage = "Please Enter Last Name", AllowEmptyStrings = true)]  
        public string DSurname { get; set; } = null!;  
        public string? DTelephone { get; set; }  
  
        [DataType(DataType.EmailAddress, ErrorMessage = "E-mail is not valid")]  
        [EmailAddress(ErrorMessage = "E-mail is not valid")]  
        [Required(ErrorMessage = "Please Select Email Address", AllowEmptyStrings = true)]  
        public string? DEmail { get; set; }   
  
        [Required(ErrorMessage = "Please Enter Address", AllowEmptyStrings = true)]  
        public string? DAddress1 { get; set; }   
        public string? DAddress2 { get; set; }   
        public string? DAddress3 { get; set; }   
  
        [Required(ErrorMessage = "Please Select Town")]  
        public int DTown { get; set; }   
  
        [Required(ErrorMessage = "Please Select County")]  
        public int DCounty { get; set; }   
  
        public int DCountry { get; set; }  
  
        [Required(ErrorMessage = "Please Select Town", AllowEmptyStrings = true)]  
        public string? DTownNonUK { get; set; }   
  
        [Required(ErrorMessage = "Please Select County", AllowEmptyStrings = true)]  
        public string? DCountyNonUK { get; set; }   
  
        public string? DCountryName { get; set; }  
  
        [Required(ErrorMessage = "Please Enter Country")]  
        public int? DCountryNonUK { get; set; }   
  
        [Required(ErrorMessage = "Please Enter Postcode", AllowEmptyStrings = true)]  
        public string? DZip { get; set; }  
        public bool IsUkAddress { get; set; } = false;  
  
        [Required(ErrorMessage = "Enter Enquiry Message", AllowEmptyStrings = true)]  
        public string? EnquiryMessage { get; set; }   
        public IEnumerable<County>? Counties { get; set; }  
        public IEnumerable<Town>? Towns { get; set; }  
        public IEnumerable<TownCountyViewModel>? TownCounties { get; set; }  
        public IEnumerable<Country>? UkCountries { get; set; }  
        public IEnumerable<Country>? NonUkCountries { get; set; }  
        public string? LicNbr { get; set; }  
        public bool? IsBooking { get; set; }  
        public decimal FullNetAmount { get; set; }   
        public decimal OnlineDiscount { get; set; }  
        public decimal DiscountedPrice { get; set; }  
        public decimal BKHireCharges { get; set; }   
        public decimal NetExtrasAmount { get; set; }   
        public decimal OpeningHrsSurcharge { get; set; }  
        public decimal OpeningHrsSurchargeNet { get; set; }   
        public decimal OpeningHrsSurchargeVat { get; set; }   
        public decimal? VATPercentage { get; set; }   
        public decimal WeekendDaysSurcharge { get; set; }   
  
    }  


 public class CreateEnquiryViewModel  
    {  
        public int Id { get; set; }  
        public string? Code { get; set; }  
        public string Title { get; set; } = null!;  
        public string FirstName { get; set; } = null!;  
        public string SurName { get; set; } = null!;  
        public string? Telephone { get; set; }   
        public string? Email { get; set; }  
        public Nullable<int> TownId { get; set; }  
        public string? TownName { get; set; }  
        public Nullable<int> CountyId { get; set; }  
        public string? CountyName { get; set; }   
        public Nullable<int> CountryId { get; set; }  
        public string? CountryName { get; set; }   
        public string? Address1 { get; set; }  
        public string? Address2 { get; set; }   
        public string? Address3 { get; set; }   
        public string? Postcode { get; set; }   
        public Nullable<bool> IsUkAddress { get; set; }  
        public int FranchiseId { get; set; }  
        public string? FranchiseName { get; set; }   
        public Nullable<int> SubofficeId { get; set; }  
        public string? SubOfficeName { get; set; }  
        public Nullable<System.DateTime> StartDate { get; set; }  
        public Nullable<System.TimeSpan> StartTime { get; set; }  
        public Nullable<System.DateTime> EndDate { get; set; }  
        public Nullable<System.TimeSpan> EndTime { get; set; }  
        public Nullable<int> Group_Id { get; set; }  
        public string? GroupName { get; set; }   
        public Nullable<short> FleetCategory_Id { get; set; }  
        public string? FleetCategoryName { get; set; }  
        public Nullable<decimal> Price { get; set; }  
        public Nullable<decimal> PricePerDay { get; set; }  
        public string? EnquiryMessage { get; set; }   
        public string? AdditionalInfo { get; set; }   
        public string? EnquiryStatus { get; set; }   
        public System.DateTime CreatedOn { get; set; }  
        public Nullable<System.DateTime> ModifiedOn { get; set; }  
    }  

and this is the web api service

  [HttpPost("payment")]  
        public async Task<string> ProceedPayment([FromBody] YourBookingVM bp)  
        {  
           return  "Ok";  
       }  

and the client side call is as following with parameter (RequestPayload)

"{"bp":{"HomeSearch":{"Branch":"TRAINING 1","PickupLocId":"F-16282","FranchiseId":"16282","SubofficeId":0,"StartDate":"2022-07-02T05:00:00.000Z","StartTime":"10:00:00","EndDate":"2022-07-03T05:00:00.000Z","EndTime":"10:00:00","VehicleType":"CAR","VehicleCategoryId":"1","IsNewSearch":true,"BookingDays":1,"ChargedDays":1},"CurrentCarDetails":"{\"Name\":\"CORSA COMFORT 16V\",\"Group\":\"Small 5 Door \",\"Price\":32,\"Id\":18,\"TariffId\":null,\"PerDayPrice\":\"32.00\",\"DefaultImage\":\"/SiteResources/HeadOffice/WebGroup/WebGroupIcon/f59d1364-c484-4ebb-b52c-c5ff9dff454a.jpg\"}","CurrentExtras":"[{\"Id\":6026,\"Name\":\"Additional Driver Daily Charge\",\"NetPrice\":\"20.00\",\"VatPercentage\":\"20.00\",\"VatAmount\":\"1.20\",\"PriceWithVatPerDay\":\"24.00\",\"Total\":\"24.00\",\"Quantity\":\"1\",\"Vat\":1.2,\"ChargePerDay\":true}]","PaymentDetails":{"Amount":56,"VATPercentage":0,"Token":"123","ClientKey":"T_C_2d7658e8-12b4-4c82-814a-e8fe5ac73ed6","CardType":"6","CardNumber":"4444","ExpiryMonth":"12","ExpiryYear":"2022","CVC":"123","DTitle":"Mr","DFirstName":"meh","DSurname":"ahm","DTelephone":"3434343","DEmail":"******@gmail.com","LicNbr":"dfd34343","IsUkAddress":false,"DZip":"b11sa","DAddress1":"  Apartment 1, Ridley House","DAddress2":"1 Ridley Street","DTown":5080,"DTownNonUK":"Birmingham","DCounty":3817,"DCountyNonUK":"westmidlands","DCountryName":"","DCountryNonUK":"","PTitle":"Mr","PFirstName":"meh","PSurname":"ahm","PTelephone":"3434343","PIsUkAddress":true,"PZip":"b11sa","PAddress1":"  Apartment 1, Ridley House","PAddress2":"1 Ridley Street","PTown":5080,"PTownNonUK":"Birmingham","PCounty":3817,"PCountyNonUK":"westmidlands","PCountryNonUK":""}}}"  

and following is the await fetch call

 const submitPaymentForm = async (payment) => {  
      let resultPaymentPage = [];  
        const settingsPaymentPage = {  
            method: "POST",  
            headers: {  
                "Content-Type": "application/json"  
            },  
            body: JSON.stringify({ bp: requestPaymentObj })  
        };  
        try {  
            const responsePaymentPage = await fetch(''api/Rental/ayment', settingsPaymentPage);  
            if (responsePaymentPage && !responsePaymentPage.ok) {  
                resultDriverDetailPage = [];  
            }  
            else {  
                resultPaymentPage = await responsePaymentPage.json();                  
      
            }  
        } catch (e) {  
            console.log(e);  
        }  
    }  

217021-image.png

There is none error in it, request goes to the server side but my bp object is null and all child objects are null as well.

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 60,161 Reputation points
    2022-07-01T14:25:21.663+00:00

    Your client side data is nested one too many, on cursory glance. The name of the model parameter on the server side is not part of the body data. What happens is that the server will automatically create an instance of the parameter (YourBookingVM) and then it will enumerate the form data/JSON and try to match each value provided with the corresponding name (case sensitive or insensitive is configurable) of a property on the model. Hence if you send

       {  
          "IsEnquiry": true    
       }  
    

    Then the IsEnquiry property will be set on the model that the runtime created for your parameter. It does the same thing for child objects if they are actually assigned values otherwise they are left blank.

    In your data you're sending a root element of bp. There is no bp property on YourBookingVM so it ignores that entire object. Promote all the data inside that JSON object to the root and remove the field and see if your problem goes away.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-07-01T15:22:00.707+00:00

    change:

             body: JSON.stringify({ bp: requestPaymentObj })  
    

    to:

             body: JSON.stringify(requestPaymentObj)
    
    1 person found this answer helpful.
    0 comments No comments

  2. mehmood tekfirst 771 Reputation points
    2022-07-01T15:41:36.443+00:00

    Thank you Cooldadtx and Bruce for the guidance. My issue has been solved now.

    There was some mandatory fields in payment class.

    I am now sending these fields . and Now data is coming through it.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.