2

I want to send a post request and add data to the database table.

Here is my model:

public partial class PaymentMethods
{
    public PaymentMethods()
    {
        PaymentToUser = new HashSet<PaymentToUser>();
    }

    public int Id { get; set; }
    public int? CardNumber { get; set; }
    public int? Month { get; set; }
    public int? Year { get; set; }
    public int? Cvv { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Index { get; set; }
    public string Country { get; set; }

    public ICollection<PaymentToUser> PaymentToUser { get; set; }
}

Here is the Controller method that receives POST request:

[HttpPost]
public JsonResult AddPaymentMethod(PaymentMethods payment)
{
     string result;
     if(ModelState.IsValid)
     {
         _context.PaymentMethods.Add(payment);
         _context.SaveChanges();
         result = "Added";
     }
     else
     {
         result = "Error";
     }

     return Json(result);
}

And here is the JSON that I am sending via Postman:

{ "CardNumber": 2345678912343456, "Month": 10, "Year": 20, "CVV": 322, "Name": "Eugene", "Surname": "Sukhomlyn", "Index": 83050, "Country": "UA" }

So I think all great with data, but I get the empty object in controller method on the post, where is my error?

10
  • 1
    2.3 quadrillion definitely won't fit into an int. I suspect a credit card number should probably be a string, no? Do you ever need to perform math on a credit card number? Commented Aug 29, 2018 at 20:32
  • Thank;s for suggestion @David Commented Aug 29, 2018 at 20:34
  • But it not helps with empty objects in DB @David Commented Aug 29, 2018 at 20:46
  • 1
    @David You may not do math on it directly. But you might be surprised to find out that a Luhn algorithm is implemented for many credit card numbers. I found out about this algorithm when working on medical provider numbers in the healthcare industry and thought it was really neat. Commented Aug 29, 2018 at 20:53
  • 1
    @EugeneSukh You need to add [FromBody] before the input parameter like this: public JsonResult AddPaymentMethod([FromBody] PaymentMethods payment) Commented Aug 29, 2018 at 21:14

1 Answer 1

2

Try putting [FromBody] in method parameter if you are passing json from body.

Sign up to request clarification or add additional context in comments.

1 Comment

This is really more of a comment than an answer. I see that you are new to Stack Overflow, you can comment once you receive 50 reputation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.