如何在 ASP MVC 中将所有动态添加的文本框保存到数据库中的两列?

How to save all dynamically added textbox to two column in database in ASP MVC?

美好的一天!我在将我的输入保存在具有两个数据库列的动态添加的文本框脚本中时遇到问题。 Id、EmployeeId、类别和金额。我只想将动态文本框中输入的所有数据保存到数据库中。

这是我在 ASP MVC 视图中使用脚本添加动态文本框的代码:

@using PayrollWeb.Models
@model PayrollWeb.Models.PayrollFormModel
@{
    ViewBag.Title = "AddOrEdit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm("AddOrEdit", "Payroll", FormMethod.Post, new { onsubmit = "return SubmitFormPayroll(this)" }))
{
    @Html.HiddenFor(model => model.Id)

    <h1 style="text-align: center;"><span class="fa fa-calculator"></span>&nbsp;Payroll</h1>
    <br />
<div class="panel-group col-md-12">
    <div class="panel panel-primary">
        <div class="panel-heading">
            Employee Details
        </div>
        <div class="panel-body">
            <div class="row">
                <div class="col-md-3">
                    <div class="form-group">
                        @Html.LabelFor(x => x.EmployeeId, new { @class = "form-label" })
                        @Html.DropDownListFor(x => x.EmployeeId, Model.Employees, "", new { @class = "form-control" })
                        @Html.ValidationMessageFor(x => x.EmployeeId, null, new { @class = "text-danger" })
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        @Html.LabelFor(x => x.StartDate, new { @class = "form-label" })
                        @Html.TextBoxFor(x => x.StartDate, new { @class = "form-control", @id = "datepickerto", @type = "date" })
                        @Html.ValidationMessageFor(x => x.StartDate, null, new { @class = "text-danger" })
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        @Html.LabelFor(x => x.EndDate, new { @class = "form-label" })
                        @Html.TextBoxFor(x => x.EndDate, new { @class = "form-control", @id = "datepickertodin", @type = "date" })
                        @Html.ValidationMessageFor(x => x.EndDate, null, new { @class = "text-danger" })
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        @Html.LabelFor(x => x.PayDate, new { @class = "form-label" })
                        @Html.TextBoxFor(x => x.PayDate, new { @class = "form-control", @id = "datepickertodin", @type = "date" })
                        @Html.ValidationMessageFor(x => x.PayDate, null, new { @class = "text-danger" })
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-3">
                    <div class="form-group">
                        @Html.LabelFor(x => x.PayFrequency, new { @class = "form-label" })
                        @Html.TextBoxFor(x => x.PayFrequency, new { @class = "form-control", @Value = "BI-WEEKLY", @readonly = "readonly" })
                        @Html.ValidationMessageFor(x => x.PayFrequency, null, new { @class = "text-danger" })
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        @Html.LabelFor(x => x.DaysWorked, new { @class = "form-label" })
                        @Html.TextBoxFor(x => x.DaysWorked, new { @class = "form-control" })
                        @Html.ValidationMessageFor(x => x.DaysWorked, null, new { @class = "text-danger" })
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        @Html.LabelFor(x => x.MonthlyRate, new { @class = "form-label" })
                        @Html.TextBoxFor(x => x.MonthlyRate , new { @class = "form-control", @id="monthlyrate"})
                        @Html.ValidationMessageFor(x => x.MonthlyRate, null, new { @class = "text-danger" })
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

        @*<div class="form-group">
                @Html.LabelFor(x => x.SalaryPerDay, new { @class = "form-label" })
                @Html.TextBoxFor(x => x.SalaryPerDay, new { @class = "form-control", @id = "salaryperday" })
            </div>

            <div class="form-group">
                @Html.LabelFor(x => x.WorkDays, new { @class = "form-label" })
                @Html.TextBoxFor(x => x.WorkDays, new { @class = "form-control", @id = "workdays" })
            </div>*@
    <div class="panel-group col-md-4">
        <div class="panel panel-primary">
            <div class="panel-heading">
                Income
            </div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-md-6"></div>
                    <div class="col-md-6">
                        <div class="form-group">
                            @Html.LabelFor(x => x.BasicPayAmount, new { @class = "form-label" })
                            @Html.TextBoxFor(x => x.BasicPayAmount, new { @class = "form-control", @id = "basicpayamount" })
                            @Html.ValidationMessageFor(x => x.BasicPayAmount, null, new { @class = "text-danger" })
                        </div>
                    </div>
                </div>            
            </div>
        </div>
    </div>

<div class="panel-group col-md-4">
    <div class="panel panel-primary">
        <div class="panel-heading">
            Deductions
        </div>
        <div class="panel-body">
            <div class="form-group">
                @Html.LabelFor(x => x.WitholdingTax, new { @class = "form-label" })
                @Html.TextBoxFor(x => x.WitholdingTax, new { @class = "form-control" })
                @Html.ValidationMessageFor(x => x.WitholdingTax, null, new { @class = "text-danger" })
            </div>
            <div class="form-group">
                @Html.LabelFor(x => x.PagibigContribution, new { @class = "form-label" })
                @Html.TextBoxFor(x => x.PagibigContribution, new { @class = "form-control", @Value = "100.00", @readonly = "readonly" })
                @Html.ValidationMessageFor(x => x.PagibigContribution, null, new { @class = "text-danger" })
            </div>
            <div class="form-group">
                @Html.LabelFor(x => x.PhilhealthContribution, new { @class = "form-label" })
                @Html.TextBoxFor(x => x.PhilhealthContribution, new { @class = "form-control", @Value = "191.25", @readonly = "readonly" })
                @Html.ValidationMessageFor(x => x.PhilhealthContribution, null, new { @class = "text-danger" })
            </div>
            <div class="form-group">
                @Html.LabelFor(x => x.SSSContribution, new { @class = "form-label" })
                @Html.TextBoxFor(x => x.SSSContribution, new { @class = "form-control", @Value = "560.00", @readonly = "readonly" })
                @Html.ValidationMessageFor(x => x.SSSContribution, null, new { @class = "text-danger" })
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        @Html.LabelFor(x => x.Deduction, new { @class = "form-label" })
                        @Html.TextBoxFor(x => x.Deduction, new { @class = "form-control", @id = "deduction" })
                        @Html.ValidationMessageFor(x => x.Deduction, null, new { @class = "text-danger" })
                    </div>
                </div>
                <div class="col-md-6">
                    <input id="btnAdd" type="button" value="Add" onclick="AddTextBox()" class="btn btn-info" style="margin-top: 25px;" />
                </div>
            </div>
            <div id="TextBoxContainer" style="margin-top: 6%;   ">
                <!--Textboxes will be added here -->
            </div>
            <br />
            <div class="form-group">
                @Html.LabelFor(x => x.CashLoan, new { @class = "form-label" })
                @Html.TextBoxFor(x => x.CashLoan, new { @class = "form-control" })
                @Html.ValidationMessageFor(x => x.CashLoan, null, new { @class = "text-danger" })
            </div>
        </div>
    </div>
</div>

<div class="panel-group col-md-4">
    <div class="panel panel-primary">
        <div class="panel-heading">
            Summary
        </div>
        <div class="panel-body">
            <div class="form-group">
                @Html.LabelFor(x => x.TotalSalary, new { @class = "form-label" })
                @Html.TextBoxFor(x => x.TotalSalary, new { @class = "form-control", @id = "totalsalary" })
                @Html.ValidationMessageFor(x => x.TotalSalary, null, new { @class = "text-danger" })
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-4"></div>
    <div class="col-md-4"></div>
    <div class="col-md-2"></div>
    <div class="col-md-2">
        <div class="form-group">
            <input type="submit" value="Submit" class="btn btn-primary" />
            <input type="reset" value="Reset" class="btn btn-primary" />
        </div>
    </div>
</div>

    <a href="@Url.Action("Index", "Payroll")"><span class="fa fa-backward"></span>&nbsp;&nbsp;Back to Dashboard</a>

    <script type="text/javascript">
        function GetDynamicTextBox(value) {
            var div = $("<div />").attr("class", "row").attr("style","margin-top: 6px;");

            var textBox = $("<input />").attr("type", "textbox").attr("name", "DynamicTextBox").attr("style", "width:30%;margin-left:5%;");
            textBox.val(value);
            div.append(textBox);


            var textBox = $("<input />").attr("type", "textbox").attr("name", "DynamicTextBox1").attr("style", "width:30%;margin-left:5%;");
            textBox.val(value);
            div.append(textBox);

            var button = $("<input />").attr("type", "button").attr("value", "Remove").attr("style", "width:20%;margin-left:5%;");
            button.attr("onclick", "RemoveTextBox(this)");
            div.append(button);

            return div;

        }
        function AddTextBox() {
            var div = GetDynamicTextBox("");
            $("#TextBoxContainer").append(div);
        }

        function RemoveTextBox(button) {
            $(button).parent().remove();
        }

        $(function () {
            var values = eval('@Html.Raw(ViewBag.Values)');
            if (values != null) {
                $("#TextBoxContainer").html("");
                $(values).each(function () {
                    $("#TextBoxContainer").append(GetDynamicTextBox(this));
                });
            }
        });
                //$(function () {
                //    $('#datepickerto').datepicker({ //datepicker startdate
                //        dateFormat: "yy/mm/dd",
                //        changeMonth: true,
                //        changeYear: true,
                //        showOn: "both",
                //        buttonText : "<i class='fa fa-calendar'></i>"
                //    });
                //});
                //$(function () {
                //    $('#datepickertodin').datepicker({ //datepicker enddate
                //        dateFormat: "yy/mm/dd",
                //        changeMonth: true,
                //        changeYear: true,
                //        showOn: "both",
                //        buttonText: "<i class='fa fa-calendar'></i>"
                //    });
                //});

                //$(function () { //calculate

                //    $("#salaryperday,#workdays,#deduction").keyup(function (e) {

                //        var salary = $("#salaryperday").val();
                //        var work = $("#workdays").val();
                //        var deduction = $("#deduction").val();
                //        var result = "";

                //        if (salary !== "" && work !== "" && deduction !== "" && $.isNumeric(salary) && $.isNumeric(work) && $.isNumeric(deduction)) {
                //            result = parseFloat(salary) * parseFloat(work) - parseFloat(deduction);
                //        }
                //        $("#totalsalary").val(result);

                //    });

                //});

                $(function () { //calculate

                    $("#monthlyrate").keyup(function (e) {

                        var monthlyrate = $("#monthlyrate").val();
                        var result = "";

                        if (monthlyrate !== "" && $.isNumeric(monthlyrate)) {
                            result = parseFloat(monthlyrate) / 2;
                        }
                        $("#basicpayamount").val(result);

                    });

                });
    </script>
}

这是我的控制器。我将 foreach 用于我的字符串。:

using PayrollWeb.DB.Core;
using PayrollWeb.DB.Data;
using PayrollWeb.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace PayrollWeb.Controllers
{
    public class PayrollController : Controller
    {
        // GET: Payroll
        private PayrollwebContext db = new PayrollwebContext(); //connection
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetData()
        {
            var payrolls = (from p in db.Payrolls.ToList()
                            join e in db.Employees.ToList() on p.EmployeeId equals e.Id

                            select new PayrollListModel
                            {
                                Id = p.Id,
                                EmployeeName = e.FirstName + " " + e.MiddleName + " " + e.LastName,
                                StartDate = Convert.ToDateTime(p.StartDate),
                                EndDate = Convert.ToDateTime(p.EndDate),
                                Deduction = p.Deduction,
                                TotalSalary = p.TotalSalary
                            });
            return Json(new { data = payrolls.ToList() }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AddOrEdit(int? id)
        {
            var model = new PayrollFormModel();

            if (id != null)
                model.Id = Convert.ToInt32(id);

            model = PreparePayrollFormModel(model);

            return View(model);
        }

        //[Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult AddOrEdit(PayrollFormModel model, string[] DynamicTextBox, string[] DynamicTextBox1)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            ViewBag.Values = serializer.Serialize(DynamicTextBox);
            ViewBag.Values = serializer.Serialize(DynamicTextBox1);

            foreach (string textboxValue in DynamicTextBox)
            {
                bool resetLoop = false;
                foreach (string textboxValue1 in DynamicTextBox1)
                {
                    using (var db = new PayrollwebContext())
                    {
                        if (model.Id > 0)
                        { // update
                            var EmployeePayroll = db.Payrolls.FirstOrDefault(x => x.Id == model.Id);

                            EmployeePayroll.Id = model.Id;
                            EmployeePayroll.EmployeeId = model.EmployeeId;
                            EmployeePayroll.StartDate = model.StartDate;
                            EmployeePayroll.EndDate = model.EndDate;
                            EmployeePayroll.PayFrequency = model.PayFrequency;
                            EmployeePayroll.PayDate = model.PayDate;
                            EmployeePayroll.DaysWorked = model.DaysWorked;
                            EmployeePayroll.MonthlyRate = model.MonthlyRate;
                            EmployeePayroll.WitholdingTax = model.WitholdingTax;
                            EmployeePayroll.PagibigContribution = model.PagibigContribution;
                            EmployeePayroll.PhilhealthContribution = model.PhilhealthContribution;
                            EmployeePayroll.SSSContribution = model.SSSContribution;
                            //EmployeePayroll.SalaryPerDay = model.SalaryPerDay;
                            //EmployeePayroll.WorkDays = model.WorkDays;
                            EmployeePayroll.Deduction = model.Deduction;
                            EmployeePayroll.CashLoan = model.CashLoan;
                            EmployeePayroll.TotalSalary = model.TotalSalary;

                            db.Payrolls.AddOrUpdate(EmployeePayroll);
                            db.SaveChanges();
                            return Json(new { success = true, message = "Updated Successfully" }, JsonRequestBehavior.AllowGet);
                        }
                        else
                        { //insertion
                            var payrolls = new Payroll
                            {
                                EmployeeId = model.EmployeeId,
                                StartDate = model.StartDate,
                                EndDate = model.EndDate,
                                PayFrequency = model.PayFrequency,
                                PayDate = model.PayDate,
                                DaysWorked = model.DaysWorked,
                                MonthlyRate = model.MonthlyRate,
                                BasicPayAmount = model.BasicPayAmount,
                                WitholdingTax = model.WitholdingTax,
                                PagibigContribution = model.PagibigContribution,
                                PhilhealthContribution = model.PhilhealthContribution,
                                SSSContribution = model.SSSContribution,
                                //SalaryPerDay = model.SalaryPerDay,
                                //WorkDays = model.WorkDays,
                                Deduction = model.Deduction,
                                CashLoan = model.CashLoan,
                                TotalSalary = model.TotalSalary
                            };
                            db.Payrolls.Add(payrolls);

                            var deduct = new Deductions
                            {
                                EmployeeId = payrolls.EmployeeId,
                                Category = textboxValue,
                                Amount = Convert.ToInt32(textboxValue1),

                            };
                            db.Deductionss.Add(deduct);
                            db.SaveChanges();
                            //resetLoop = false;
                            //return Json(new { success = true, message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
                        }
                    }
                    //resetLoop = true;
                    //break;
                }
                //resetLoop = false;
            }
            model = PreparePayrollFormModel(model);
            return View(model);
        }

        public PayrollFormModel PreparePayrollFormModel(PayrollFormModel model) //model null
        {
            model.Employees = db.Employees.Select(x => new SelectListItem //laman ng dropdown
            {
                Text = x.FirstName + " " + x.MiddleName + " " + x.LastName,
                Value = x.Id.ToString()
            });

            if (model.Id > 0) //edit din to para magreturn ng value
            {
                var payroll = db.Payrolls.Find(model.Id); //null

                model.EmployeeId = payroll.EmployeeId;
                model.StartDate = payroll.StartDate;
                model.EndDate = payroll.EndDate;
                //model.SalaryPerDay = payroll.SalaryPerDay;
                //model.WorkDays = payroll.WorkDays;
                model.Deduction = payroll.Deduction;
                model.TotalSalary = payroll.TotalSalary;

                model.Employees = db.Employees.Select(x => new SelectListItem //laman ng dropdown
                {
                    Text = x.FirstName + " " + x.MiddleName + " " + x.LastName,
                    Value = x.Id.ToString()
                });
            }
            return model;
        }

        [HttpPost]
        public ActionResult Delete(PayrollFormModel model)
        {
            if (model.Id > 0)
            {
                var orders = db.Payrolls.FirstOrDefault(x => x.Id == model.Id);
                db.Payrolls.Remove(orders);
                db.SaveChanges();
                return Json(new { success = true, message = "Deleted Successfully" }, JsonRequestBehavior.AllowGet);
            }
            return View(model);
        }
    }
}

提前致谢。

你的意思是你想插入或更新工资单一次,并用string[] DynamicTextBox, string[] DynamicTextBox1添加扣除额。如果是这样,你可以这样做: 控制器:

JavaScriptSerializer serializer = new JavaScriptSerializer();
ViewBag.Values = serializer.Serialize(DynamicTextBox);
ViewBag.Values = serializer.Serialize(DynamicTextBox1);
using (var db = new PayrollwebContext())
{
    if (model.Id > 0)
    { // update
        var EmployeePayroll = db.Payrolls.FirstOrDefault(x => x.Id == model.Id);

        EmployeePayroll.Id = model.Id;
        EmployeePayroll.EmployeeId = model.EmployeeId;
        EmployeePayroll.StartDate = model.StartDate;
        EmployeePayroll.EndDate = model.EndDate;
        EmployeePayroll.PayFrequency = model.PayFrequency;
        EmployeePayroll.PayDate = model.PayDate;
        EmployeePayroll.DaysWorked = model.DaysWorked;
        EmployeePayroll.MonthlyRate = model.MonthlyRate;
        EmployeePayroll.WitholdingTax = model.WitholdingTax;
        EmployeePayroll.PagibigContribution = model.PagibigContribution;
        EmployeePayroll.PhilhealthContribution = model.PhilhealthContribution;
        EmployeePayroll.SSSContribution = model.SSSContribution;
        //EmployeePayroll.SalaryPerDay = model.SalaryPerDay;
        //EmployeePayroll.WorkDays = model.WorkDays;
        EmployeePayroll.Deduction = model.Deduction;
        EmployeePayroll.CashLoan = model.CashLoan;
        EmployeePayroll.TotalSalary = model.TotalSalary;

        db.Payrolls.AddOrUpdate(EmployeePayroll);
        db.SaveChanges();
        return Json(new { success = true, message = "Updated Successfully" }, JsonRequestBehavior.AllowGet);
    }
    else
    { //insertion
        var payrolls = new Payroll
        {
            EmployeeId = model.EmployeeId,
            StartDate = model.StartDate,
            EndDate = model.EndDate,
            PayFrequency = model.PayFrequency,
            PayDate = model.PayDate,
            DaysWorked = model.DaysWorked,
            MonthlyRate = model.MonthlyRate,
            BasicPayAmount = model.BasicPayAmount,
            WitholdingTax = model.WitholdingTax,
            PagibigContribution = model.PagibigContribution,
            PhilhealthContribution = model.PhilhealthContribution,
            SSSContribution = model.SSSContribution,
            //SalaryPerDay = model.SalaryPerDay,
            //WorkDays = model.WorkDays,
            Deduction = model.Deduction,
            CashLoan = model.CashLoan,
            TotalSalary = model.TotalSalary
        };
        db.Payrolls.Add(payrolls);
        List<Deductions> list = new List<Deductions>();
        for (int i = 0; i < DynamicTextBox.Length; i++)
        {
            var deduct = new Deductions
            {
                EmployeeId = payrolls.EmployeeId,
                Category = DynamicTextBox[i],
                Amount = Convert.ToInt32(DynamicTextBox1[i]),
            };
            list.Add(deduct);
        }
        db.Deductionss.AddRange(list);
        db.SaveChanges();
        //resetLoop = false;
        //return Json(new { success = true, message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
    }
    model = PreparePayrollFormModel(model);
    return View(model);