Eugene Sukh
Eugene Sukh

Reputation: 2727

Post request is empty (ASP.NET Core)

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?

Upvotes: 2

Views: 1991

Answers (1)

Lokesh Agarwal
Lokesh Agarwal

Reputation: 107

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

Upvotes: 2

Related Questions