如何将HTML(View)表数据传递给控制器​​以保存在slq表中

时间:2019-06-15 01:54:14

标签: asp.net-core

我正在根据上个月可用的数据计算一些值,并以表格格式显示在视图中。我有另一个模型,我需要传递这些值并将其保存在数据库中。我没有输入任何值,值是静态的或计算得出的。值不会从视图传递到控制器。

我尝试了jquery / ajax,但是没有成功。

//控制器//

[HttpPost]
        public JsonResult Proccess(List<ServerCount> deviceCounts)
        {
            if(deviceCounts == null)
            {
                deviceCounts = new List<ServerCount>();
            }

            var startOfTthisMonth = new DateTime(DateTime.Today.Year,
                DateTime.Today.Month, 1);
            var FromDate = startOfTthisMonth.AddMonths(-1);
            var ToDate = startOfTthisMonth.AddDays(-1);
            var billMonth = startOfTthisMonth.AddMonths(-1).ToString("MMM") + "-" + startOfTthisMonth.AddMonths(-1).ToString("yyyy");

            ServerCount model = new ServerCount();

            foreach (ServerCount sc in deviceCounts)
            {
                model.BillingMonth = billMonth;
                model.ServiceName = sc.ServiceName;
                model.BaslineVol = sc.BaslineVol;
                model.ResourceUnit = sc.ResourceUnit;
                model.DeviceCount = sc.DeviceCount;
                model.DeployedServer = sc.DeployedServer;
                model.RetiredServer = sc.RetiredServer;
                _context.ServerCount.Add(model);
            }

            int insertRecords = _context.SaveChanges();

            return Json(insertRecords);
        }

==================
Jquery
<script type="text/javascript">
    $(document).ready(function () {
        $("body").on("click", "#btnSave", function () {
            var deviceCounts = new Array();
            $("#tblServerCount TBODY TR").each(function () {
                var row = $(this);
                var deviceCount = {};
                deviceCount.ServiceName = row.find("TD").eq(0).html();
                deviceCount.BaslineVol = row.find("TD").eq(1).html();
                deviceCount.ResourceUnit = row.find("TD").eq(2).html();
                deviceCount.DeviceCount = row.find("TD").eq(3).html();
                deviceCount.DeployedServer = row.find("TD").eq(4).html();
                deviceCount.RetiredServer = row.find("TD").eq(5).html();
                deviceCounts.push(deviceCount);
            });

            var model = $("#MyForm").serialize();
            $.ajax({
                type: "POST",
                url: '@Url.Action("Proccess", "DeviceCountServers", new { Area = "Admin" })?' +model,
                data: JSON.stringify(deviceCounts),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    alert(r + " record(s) inserted.");
                    location.reload();
            });
        });
    });
</script>

我希望通过单击按钮将表中的数据保存到sql

0 个答案:

没有答案