Home > Net >  Post Model to Controller in ajax
Post Model to Controller in ajax

Time:10-15

This is My ajax Code

      $('#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')
                }
            })
        })

This is My Controller

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

and This My Model

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

and this is my view

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

My problem is when I use the code $('#formData').serialize(). It can convert the data in View into Model normally. But when I use JSON.serialize(view), It can't achieve the same goal. Even if I add [FormBody] to the Action, I cannot get any relevant information. Any suggestions?

CodePudding user response:

JSON.serialize is not exists in js,we usually use JSON.stringify.And you need to make sure the model structure of view is the same with model RightsModel.And you need to add contentType:"application/json", to ajax since you want to pass json type data to action.Here is a demo:

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')
                }
            })
        })

action:

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

result: enter image description here

I try yo use var ID = ["1", "2", "3"]; to test,and it can work.ID need to be type List<string>.

  • Related