Post ajax 中的模型到控制器

Post Model to Controller in ajax

这是我的ajax代码

      $('#RolesSave').click(function () {
            var sRow = JSON.parse(JSON.stringify($('#table').bootstrapTable('getSelections')));
            var ID = JSON.stringify(sRow, ["ID"]);

            var view = {
                CompanyCode: $('#Company').val(),
                RolesCode: $('#Roles').val(),
                ID,
            };

            $.ajax({
                method: "POST",
                url: '@Url.Action("Save")',
                data: $('#formData').serialize(),
                success: function (data) {
                    alert(data + '!!!')
                },
                error: function () {
                    alert('ERROR')
                }
            })
        })

这是我的控制器

    [HttpPost]
    public IActionResult Save(RightsModel view)
    {
        return View();
    }

这是我的模特

public class RightsModel
{
    public List<string> ID { get; set; }
    public string Company { get; set; }
    public string Roles { get; set; }
}

这是我的观点

<form id="formData">
@Html.DropDownListFor(m => m.Company, Model.Company)
@Html.DropDownListFor(m => m.Roles, Model.Roles)
<button id="RolesSave" class="btn btn-primary btn-light" type="submit">存檔</button>
<table id="table"></table>

我的问题是当我使用代码 $('#formData').serialize() 时。它可以正常地将View中的数据转换成Model。 但是当我使用 JSON.serialize(view) 时,它无法达到同样的目的。 即使我将 [FormBody] 添加到 Action 中,我也无法获取任何相关信息。 有什么建议吗?

JSON.serialize在js中是不存在的,我们通常使用JSON.stringify。并且你需要确保视图的模型结构与模型相同RightsModel。你需要添加 contentType:"application/json", 到 ajax 因为你想将 json 类型的数据传递给 action.Here 是一个演示:

js:

$('#RolesSave').click(function () {
           var sRow = JSON.parse(JSON.stringify($('#table').bootstrapTable('getSelections')));
            var ID = [];
            sRow.forEach(function (item, index) {
                ID.push(""+item.ID);
            });
            var view = {
                Company: $('#Company').val(),
                Roles: $('#Roles').val(),
                ID: ID
            };
                $.ajax({
                method: "POST",
                    url: '@Url.Action("Save")',
                    data: JSON.stringify(view),
                    contentType:"application/json",
                success: function (data) {
                    alert(data + '!!!')
                },
                error: function () {
                    alert('ERROR')
                }
            })
        })

操作:

 [HttpPost]
    public IActionResult Save([FromBody]RightsModel view)
    {
        return View();
    }

结果:

我试试你用var ID = ["1", "2", "3"];来测试,它可以work.ID需要输入List<string>