【问题标题】:Unable to bind html table data to mvc controller Model无法将 html 表数据绑定到 mvc 控制器模型
【发布时间】:2020-05-28 03:30:00
【问题描述】:

我有这个模型

 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


    【解决方案1】:

    编辑

    我想我们俩都有点过火了。我做了一些挖掘,看起来JSON.stringify 实际上是必要的,因为 ajax 发布数据的方式;我认为您的问题实际上可能与javascript有关。当我复制你的代码时,出现了错误。我现在正在运行它,它正在工作。假设您发布的代码是复制和粘贴的,则:

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

    应该是

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

    看起来这只是数组名称的拼写错误。

    工作代码:

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

    【讨论】:

    • 代码不是复制粘贴,更改了一些命名,类型完全正确,但我再次检查并运行代码我仍然得到一个空列表:(,我有点用完了这里有很多想法,如果我说表格在弹出窗口中会有所不同吗?
    • 我是否必须在部分视图中激活某些内容?
    • 执行此操作 - 挂钩 Ajax 的错误事件并在返回时执行 document.write(JSON.stringify(error))。因为你是从 Ajax 做的,所以你看不到 MVC 所说的错误是什么。如果您转储错误,它可能会有所帮助。
    • 嗨迈克尔,我试过了,但没有错误,我试图将其更改为仅接受模型而不是 List 并且还更改了 ajax 发布请求以发送模型和控制器绑定它,但是当我发送一个数据类型为 json 的列表时,它总是空的,控制器中的 http 上下文请求也没有收到任何有效负载,所以不确定发生了什么
    • 你能用完整的代码复制和粘贴来更新 OP 吗?至少是视图和模型。
    【解决方案2】:

    你正在对你的对象进行字符串化:

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

    因此,当您的控制器需要一个列表时,您将一个字符串传递给您的控制器。

    在我的脑海中,我想说尝试只是传递对象,例如

    data: Itemslists,
    

    或者如果有理由需要将它作为字符串传递。更改您的控制器以接收字符串,然后对其进行反序列化:

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

    【讨论】:

    • 它仍然不起作用,无论是发送字符串还是只发送项目列表
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    相关资源
    最近更新 更多