1

I am working a asp.netcore web api project.

I have a model named as PaymentRequestViewModel.In that model the object PaymentMethodViewModel will not come from Front end, I have to set a default value, and also I need to change the value when I need.

The model

public class PaymentRequestViewModel
    {
        public PaymentMethodViewModel PaymentMethod { get; set; }  // the value is null when front end sent the request
        public string TransactionType { get; set; }

        //removed rest
}
public class PaymentMethodViewModel
    {
        public CardViewModel Card { get; set; }

    }

    public class CardViewModel
    {
        public string MerchantSessionKey { get; set;} = "";
        public string CardIdentifier { get; set; } = "";
     
        public Boolean Reusable { get; set; } = false;

        public Boolean Save { get; set; } = false;
    }

The request from POSTMAN

"PaymentRequest":{
  "transactionType": "Payment", 
  "PaymentMethod" :null  // i.e Frontend will not sent the values for PaymentMethod

// removed rest
}

In my controller, I changes the values of those properties

public async Task<IActionResult> Payment([FromBody] PaymentViewModel paymentViewModel)
{
   paymentViewModel.PaymentRequest.PaymentMethod.Card.Reusable = true;  // The error occur System.NullReferenceException: Object reference not set to an instance of an object.
 //removed rest
 }

Error: System.NullReferenceException: Object reference not set to an instance of an object. at TechnePaymentApi.Controllers.PublicApi.PublicOpayoPaymentController.Payment(PaymentViewModel payment

hanushic
  • 369
  • 1
  • 5
  • 19
  • 1
    `payment.PaymentRequest.PaymentMethod` is null. You need to create new instance and assign to it before accessing its inner properties. – Yong Shun Nov 24 '21 at 06:20
  • Hi,I had a mistake. I have edited my question with `paymentViewModel.PaymentRequest.PaymentMethod.Card.Reusable = true;` – hanushic Nov 24 '21 at 06:27
  • 2
    Seems to me your not initialiazing the "PaymentMethod" class. `paymentViewModel.PaymentRequest.PaymentMethod = new PaymentMethod { Card = new Card { Reusable = true }};` – Stenehr Nov 24 '21 at 06:56

0 Answers0