MVC Controller is not receiving the values that comes from the Ajax /Javascript script

Viewed 65

I debugged the JS and Ajax code with console.log. I can see that what I entered into the textbox, is displayed in the console. However, when these values are supposed to send to the controller, they are empty or null when I hover over the tbl_stuff List. Not sure where I am making a mistake.

Here is the JS:

      $("body").on("click", "#btnSave", function () {
    var table = $("table tbody");
    var array= new Array();
    table.find('tr').each(function (i) {
        var $tds = $(this).find('td'),
        Amount = $(this).find('.val').val();
        valuestoupdate = { Amount: amount };
        array.push(valuestoupdate);
    });
    $.ajax({
        type: "POST",
        url: "@Url.Action("StuffAction","Home")",
        data: JSON.stringify(array),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            alert(r + " record(s) saved.");
        }
    });

Here is the controller action:

     public JsonResult StuffAction(List<tbl_Stuff> stuffs)
    {
        int getID = (int)TempData["id"];
        TempData.Keep();
        var GetData = _context.tbl_Detail.Where(x => x.detId == getID).FirstOrDefault();
        if (GetData != null)
        {              
            foreach (tbl_Stuff moreThings in stuffs)
            {
                tbl_Stuff stuff = new tbl_Stuff();                    
                stuff.Amount = moreThings.Amount;
                _context.tbl_Stuff.Add(stuff);
            }
        }
        int insertedRecords = _context.SaveChanges();
        return Json(insertedRecords);
    }

I get an error saying that moreThings.Amount is empty. But during debugging, the JS code gets the value entered into the textbox.

1 Answers

The .Net routing can't match the request

change the action signature to public JsonResult StuffAction(List< string > stuffs)

or in your ajax call change the array to an array of objects matching the properties of tbl_Stuff

Related