0

I have this model

 public class Model
{
    public string itemlineId { get; set; }
    public string shipmentID { get; set; }
    public string containerID { get; set; }
    public string containerType { get; set; }
}

I have a dynamic html table, what im trying to do is to post table data through ajax,and send it to the controller

 $("body").on("click", "#btnSave", function () {
    //Loop through the Table rows and build a JSON array.
    var itemlists= new Array();
    $("#tblAttachShip TBODY TR").each(function () {
        var row = $(this);
        var itemList = {};
        itemList.itemlineId = row.find("TD").eq(0).html();
        itemList.shipmentID = document.getElementById("txtShipmentID").value
        itemList.containerID = row.find("TD").eq(1).html();
        itemList.containerType = row.find("TD").eq(2).html();

        itemlists.push(itemList);
    });

    //Send the JSON array to Controller using AJAX.
    $.ajax({
        type: "POST",
        url: "/Project/Create",
        data: JSON.stringify({ Model : Itemslists}),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            alert(r + " record(s) inserted.");
        }
    });
});

so far all okay, when I try to read the post request in the browser I can see that the request has the correct data as json format

Model: [{itemlineId: "aa", shipmentID: "a", containerID: "aa", containerType: "aa"}]}

however when I check the controller the list doesn't contain any elements, and no values has been binded, I checked several posts but I can't figure ouut what I did wrong to bind the json data to the model in the controller

 [HttpPost]
    public JsonResult Create(List<Model> Model)
    {


        return Json("Success");
    }

2 Answers 2

2

EDIT

I think we both jumped the gun a bit there. I did some digging and it looks like the JSON.stringify is actually going to be necessary because of the way that ajax posts the data; I think your issue might actually be with the javascript. When I copied your code, there were errors. I am running this right now which is working. Assuming your posted code was copy and pasted, this:

  data: JSON.stringify({ Model : Itemslists}),

should be

  data: JSON.stringify({ Model : itemlists}),

Looks like it was just a typo with the name of the array.

Working code:

@{
    ViewBag.Title = "Home Page";
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
        integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
        crossorigin="anonymous"></script>
<script type="text/javascript">
    $("body").on("click", "#btnSave", function () {
        //Loop through the Table rows and build a JSON array.
        var itemlists = new Array();
        $("#tblAttachShip TBODY TR").each(function () {

            var row = $(this);
            var itemList = {};
            itemList.itemlineId = row.find("TD").eq(0).html();
            itemList.shipmentID = document.getElementById("txtShipmentID").value
            itemList.containerID = row.find("TD").eq(1).html();
            itemList.containerType = row.find("TD").eq(2).html();

            itemlists.push(itemList);
        });

        //Send the JSON array to Controller using AJAX.
        $.ajax({
            url: './Home/Create',
            type: 'POST',
            data: JSON.stringify({ Model: itemlists }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                alert(r + " record(s) inserted.");
            },
            error: function (r) {
                alert(JSON.stringify(r));
            }
        });
    });
</script>

<input type="text" id="txtShipmentID" />
<table id="tblAttachShip">
    <tbody>
        <tr>
            <td>aaa</td>
            <td>aa</td>
            <td>a</td>
        </tr>
        <tr>
            <td>bbb</td>
            <td>bb</td>
            <td>b</td>
        </tr>
    </tbody>
</table>

<button id="btnSave">Save</button>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        [HttpPost]
        public JsonResult Create(List<Model> Model)
        {


            return Json(new { Message = "Success" });
        }
    }


    public class Model
    {
        public string itemlineId { get; set; }
        public string shipmentID { get; set; }
        public string containerID { get; set; }
        public string containerType { get; set; }
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

the code wasn't a copy paste, changed some naming, it's exactly correct with type, but I have checked again and run the code i still get an empty list :(, im kind of run out of ideas here, does it make a difference if I say that the table is in a pop up ?
do I have to activate something in my partial view ?
Do this - hook into the error event for the Ajax and do a document.write(JSON.stringify(error)) on the return. Because you’re doing it from Ajax you’re not seeing what MVC is saying the error is. If you dump the error it might help.
Hi Michael, i tried that but there is no error, I have tried to change it to accept only Model instead of List<Model> and also changed the ajax post request to send the Model and the controller bind it, However when I send a list as datatype json, it's always empty, the http context request in the controller also doesn't receive any payload, so not sure what is happening
Can you update the OP with a full copy and paste of the code? At least the View and the models.
0

You are stringifying your object:

data: JSON.stringify({ Model : Itemslists}),

So you are passing a string into your controller, when your controller expects a List.

Off the top of my head i'd say try just passing the object e.g.

data: Itemslists,

Or if there is a reason that you need to pass it as a string. Change your controller to receive a string and then deserialize it:

(List<Model>)serializer.Deserialize(jsonString, typeof(List<Model>);

1 Comment

it still doesn't work, both with sending a string or with just sending the itemslists

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.