Home > Back-end >  Ajax returning null value / asp.net
Ajax returning null value / asp.net

Time:03-30

I am trying to get multiple entiries with Ajax. However, both "id" and "qty" return null (By the way, I gave default values for them now.). Can you please help me? Please review my code below.

<script type="text/javascript">
$(document).ready(function () {
    $("#submit").on("click", function () {
        var elem = {};
        elem.qty = "10";
        elem.id = 1;
   
        $.ajax({
            url: '/Home/Form1/',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(elem),
            
            success: function (data) {
                alert(data),
                    console.log(data),
        
                    $("#output").html(data[0]);
            }
        });
    });
});

    public class Data
{

    public string qty { get; set; }
    public int? id { get; set; }
}

        public ActionResult Form1(Data elem)
    {

        List<Data> Elements = new List<Data>
        {
            new Data {qty=elem.qty, id=elem.id},
            };


        return Json(Elements);
    }

CodePudding user response:

"Lets focus on below code first"

        var elem = {};
        elem.qty = "10";
        elem.id = 1

Note: As you can see it already on Json fashion so you do not need to parse into json again. Therefore no need to use JSON.stringify in this case. So you could try below way:

Javascript Code:

<script>
        $(document).ready(function () {
            $("#btnSubmit").on("click", function () {
                var elem = {};
                elem.qty = "10";
                elem.id = 1;

                console.log(elem);
                $.ajax({
                    url: 'https://localhost:44361/userLog/FormPost',
                    type: 'POST',
                    dataType: 'json',
                    data: elem,
                    success: function (data) {
                        alert(data),
                            console.log(data),

                            $("#output").html(data[0]);
                    }
                });
            });

        });
    </script>

C# Controller Code:

        [HttpPost]
        public async Task<IActionResult> FormPost(Data elem)
        {
            List<Data> Elements = new List<Data>
        {
            new Data {qty=elem.qty, id=elem.id},
            };


            return Json(Elements);

        }

Output:

enter image description here

Hope it would resolved your problem as expected.

  • Related