Jquery.ajax sends null to controller, but works with hard-coded variables

Viewed 85

I was making a simple app in vs code, and I want to save values into database, this is what I have so far.

 var naziv = $("#TextNaziv").val();
        var cena = $("#TextCena").val();
        var opis = $("#TextOpis").val();

        //console.log("Cena:" + cena);
       // console.log("Opis:" + opis);
       // console.log("Naziv:" + naziv);

        var proizvod = {
            Naziv: "nazivTest123",
            Cena: 33,
            Opis: "opisTest123"
        }

       // console.log(proizvod);
        var zahtev = $.ajax({
            type: "POST",
            url: "/Home/UbaciProizvod",
            data: JSON.stringify(proizvod),
            contentType: "application/json",
            dataType: "text",

        });

And this works just fine without any problems, but when I change the var proizvod to:

var proizvod = {
     Naziv: naziv,
     Cena: cena,
     Opis: opis
        }

The app just won't save the values into the db, even tho I checked in console and the values are just fine, the controller receives null value. I tried everything I saw on the internet but nothing seems to help, maybe is some minor issue but I cannot solve it, my controller function looks like this:

public int UbaciProizvod([FromBody] Proizvod p )
{
    string upit = @"INSERT INTO Proizvod VALUES(@Naziv,@Cena,@Opis);
                            SELECT CAST(SCOPE_IDENTITY() AS int)";

        using(SqlConnection konekcija = new SqlConnection(Konekcija.CnnMagacin))
        {
            try
            {
                int id = konekcija.QuerySingleOrDefault<int>(upit,p);
                return id;

            }
            catch (System.Exception)
            {
                
               return -1;
            }
        }
}

This is my first post so every suggestion and critics are welcomed, and sorry about the variable names.

1 Answers

The difference between the two versions is that you provide Cena as an integer value in the working version, but a string in the non-working one.

To fix this call parseInt() on the value before making the AJAX request:

var proizvod = {
  Naziv: naziv,
  Cena: parseInt(cena, 10),
  Opis: opis
}
Related