ASP.NET Core MVC - 将 HTML 表转换为 json 并使用 ajax 发送到控制器

Posted

技术标签:

【中文标题】ASP.NET Core MVC - 将 HTML 表转换为 json 并使用 ajax 发送到控制器【英文标题】:ASP.NET Core MVC - Convert HTML table to json and send to controller using ajax 【发布时间】:2021-05-05 05:02:06 【问题描述】:

我正在尝试将 html 表数据发送到控制器,但似乎我做错了什么。

请看我的表格

<table id="List" class="table table-borderless">
                        <thead>
                            <tr>
                                <th>
                                    Leave ID
                                </th>
                                <th>
                                    Leave Type
                                </th>
                                <th>
                                    Date
                                </th>
                                <th>
                                    Reason
                                </th>
                                <th>
                                    Action
                                </th>
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>

这就是我使用模态向表格添加数据的方式

function AddToList() 
            var LeaveApplicationID = 1;
            var LeaveTypeID = $('#LeaveTypeID').val();
            var LeaveType = $('#LeaveTypeID').find(':selected').text();
            var Date = $('#LeaveDate').val();
            var Reason = $('#Reason').val();

            var html = '';

            html += "<tr>";
            html += "<td>" + LeaveApplicationID + "</td>";
            html += "<td>" + LeaveTypeID +"</td>";
            html += "<td>" + LeaveType + "</td>";
            html += "<td>" + Date + "</td>";
            html += "<td>" + Reason + "</td>";
            html += "<td>";
            html += "<button class='btn btn-warning btn-xs'>";
            html += "<span class='fa fa-pencil'></span>";
            html += "</button>";
            html += "<button class='btn btn-danger btn-xs'><span class='fa fa-trash'></span></button></td > ";
            html += "<tr>";

            $('#List').append(html);
        

单击按钮时,将调用函数 SaveDetails()

function SaveDetails() 

            var LeaveList = [];
            LeaveList.length = 0;

            $.each($("#List tbody tr"), function () 
                LeaveList.push(
                    LeaveApplicationID : $(this).find('td:eq(0)').html(),
                    LeaveTypeID : $(this).find('td:eq(1)').html(),
                    Date : $(this).find('td:eq(3)').html(),
                    Reason : $(this).find('td:eq(4)').html()
                );
            );

            var data = JSON.stringify(
                leaveApplicationDetails: LeaveList
            );

            console.log(data);

             $.ajax(
                contentType: 'application/json; charset=utf-8',
                dataType: "json",
                type: "POST",
                url: "@Url.Action("SaveLeaveApplicationDetails")",
                data: data,
                success: function (data) 
                    console.log(data);
                
            );
        

this is the output of the json string

根据输出我认为我得到了正确的结果

但是,当我试图发送到控制器时,我得到一个空值。

这是我的控制器。

控制器

public IActionResult SaveLeaveApplicationDetails(List<LeaveApplicationDetails> leaveApplicationDetails)
        
            
            return Json(leaveApplicationDetails);
        

你认为我哪里错了?谢谢...

已编辑:

enter image description here

output

namespace HRMS.Models

    public class LeaveApplicationHeader
    
        [Key]
        public int LeaveApplicationID  get; set; 
        public string LeaveApplicationCode  get; set; 
        public DateTime DateFiled  get; set; 
        public int EmployeeID  get; set; 
        public Employee EmployeeCode  get; set; 
        public int DepartmentID  get; set; 
        public Department DepartmentCode  get; set; 
        public int WithPay  get; set; 
        public int WithoutPay  get; set; 
        public int SLBalance  get; set; 
        public int VLBalance  get; set; 
        public int SLBalanceCertification  get; set; 
        public int VLBalanceCertification  get; set; 
        public int LeaveStatusID  get; set; 
    

    public class LeaveApplicationDetails
    
        [Key]
        public int LeaveApplicationID  get; set; 
        public int LeaveTypeID  get; set; 
        public DateTime Date  get; set; 
        public string Reason  get; set; 
    

    public class LeaveApplication
    
        public LeaveApplicationHeader LeaveApplicationHeader  get; set; 

        public LeaveApplicationDetails LeaveApplicationDetails  get; set; 
    

另一个编辑: 不工作:

$.each($("#List tbody tr"), function () 
            LeaveList.push(
                LeaveApplicationID: 1,
                LeaveTypeID: $(this).find('td:eq(1)').text(),
                Date: $(this).find('td:eq(3)').text(),
                Reason: $(this).find('td:eq(4)').text()
            );
        );

        Worked:
    

LeaveList.push(
            LeaveApplicationID: 1,
            LeaveTypeID: 1,
            Date: "2020-07-05",
            Reason: "test1"
        );
        LeaveList.push(
            LeaveApplicationID: 2,
            LeaveTypeID: 2,
            Date: "2020-07-05",
            Reason: "test2"
        );

【问题讨论】:

嗨@JeffreyEstrera,有什么更新吗? 你好我试过你的建议,但我仍然得到一个空值。 能否提供新输出的json字符串? 请看我的postt上的编辑。这是控制台上写的 var data = JSON.stringify(LeaveList); console.log(data);查看日志。 【参考方案1】:

试试这个修改:

var leaveApplicationDetails = JSON.stringify(LeaveList);

$.ajax(
    contentType: 'application/json; charset=utf-8',
    dataType: "json",
    type: "POST",
    url: "@Url.Action("SaveLeaveApplicationDetails")",
    data: leaveApplicationDetails: leaveApplicationDetails,
    success: function (data) 
        console.log(data);
    
);

【讨论】:

bruh im 仍然得到一个 null T_T huhuhu 太伤心了,我花了 3 天时间试图解决这个问题 T_T 没有JSON.stringify(只需var leaveApplicationDetails = LeaveList)你能试试吗? 还要检查你的示例 json,这都是错误的。 ID不能全部为1,因为你的第一个字段是[Key]并且你的日期格式错误(检查年份)【参考方案2】:

您只需将代码更改为

  var data = JSON.stringify(LeaveList);

然后在你的控制器中添加[FromBody]

public IActionResult SaveLeaveApplicationDetails([FromBody]List<LeaveApplicationDetails> leaveApplicationDetails)
    
        
        return Json(leaveApplicationDetails);
    

编辑

你可以像我一样尝试做一个简单的演示。

查看:

<button id="click">
click
</button>
@section Scripts

    <script>        
        $("#click").click(function() 
            var LeaveList = [];
            LeaveList.length = 0;
            LeaveList.push(
                  LeaveApplicationID: 1,
                  LeaveTypeID: 1,
                  Date: "2020-07-05",
                  Reason: "test1"
                 );
            LeaveList.push(
                LeaveApplicationID: 2,
                LeaveTypeID: 2,
                Date: "2020-07-05",
                Reason: "test2"
            );
            var data = JSON.stringify(LeaveList);
            console.log(data);
            $.ajax(
                contentType: 'application/json; charset=utf-8',
                dataType: "json",
                type: "POST",
                url: "@Url.Action("SaveLeaveApplicationDetails")",
                data: data,
                success: function (data) 
                    console.log(data);
                
            );
        )
    </script>

行动:

[HttpPost]
    public IActionResult SaveLeaveApplicationDetails([FromBody]List<LeaveApplicationDetails> leaveApplicationDetails)
    
        return Json(leaveApplicationDetails);
    

【讨论】:

以上是关于ASP.NET Core MVC - 将 HTML 表转换为 json 并使用 ajax 发送到控制器的主要内容,如果未能解决你的问题,请参考以下文章

[MVC&Core]ASP.NET Core MVC 视图传值入门

asp.net core mvc权限控制:分配权限

ASP.NET MVC Core WebAPI 项目不返回 html

ASP.NET Core MVC 入门到精通 - 3. 使用MediatR

ASP.NET Core MVC 中的慢速显示性能

如何在 ASP.Net Core MVC 中使用 HTML 链接?