无法将html表数据绑定到mvc控制器模型

问题描述 投票:0回答:2

我有这个模特

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

我有一个动态的html表,我想做的就是通过ajax发布表数据,并将其发送给控制器

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

到目前为止一切正常,当我尝试在浏览器中读取发布请求时,我可以看到该请求具有json格式的正确数据

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

但是,当我检查控制器时,列表不包含任何元素,并且没有绑定任何值,我检查了几篇文章,但是我无法弄清楚将json数据绑定到控制器中的模型时做错了什么

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


        return Json("Success");
    }
javascript c# jquery asp.net-mvc asp.net-ajax
2个回答
0
投票

您正在对对象进行字符串化:

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

因此,当控制器需要列表时,您正在将字符串传递到控制器中。

在我的头顶上,我想尝试例如只是通过物体

data: Itemslists,

或者如果出于某种原因您需要将其作为字符串传递。更改控制器以接收字符串,然后反序列化它:

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

0
投票

不要对您的JSON进行字符串化。这样做实际上是在传递字符串而不是对象。另外,您可能需要在jQuery中将传统设置为true。我记不清了,但是:https://forum.jquery.com/topic/nested-param-serialization

此:

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

应该是:

data: { Model : Itemslists},
© www.soinside.com 2019 - 2024. All rights reserved.