简体   繁体   中英

Unable to bind html table data to mvc controller Model

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");
    }

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; }
    }
}

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 eg

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>);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM