【问题标题】:Insert or save multiple rows records to database using entity framework in asp.net mvc使用asp.net mvc中的实体框架将多行记录插入或保存到数据库
【发布时间】:2020-06-22 09:08:06
【问题描述】:

我希望能够添加一个下拉列表并从中保存不同的选定值。当我添加多行时,它应该能够使用下面提供的代码从下拉列表中插入不同的值。该代码工作正常,但我想知道如何实现下拉列表部分。

查看:

   @model IEnumerable<Insert_Multiple_Rows_EF_MVC.Customer>

   @{
    Layout = null;
     }


     <table id="tblCustomers" class="table" cellpadding="0" cellspacing="0">
    <thead>
        <tr>
            <th style="width:150px">Name</th>
            <th style="width:150px">Country</th>
            <th></th>
        </tr>
        </thead>
       <tbody>
        @foreach (Customer customer in Model)
        {
            <tr>
     <td>@customer.Name</td>
     <td>@customer.Country</td>
     <td><input type="button" value="Remove" onclick="Remove(this)" /></td>
            </tr>
        }
    </tbody>
    <tfoot>
        <tr>
            <td><input type="text" id="txtName" /></td>
            <td><input type="text" id="txtCountry" /></td>
            <td><input type="button" id="btnAdd" value="Add" /></td>
        </tr>
    </tfoot>
</table>
<br />
<input type="button" id="btnSave" value="Save All" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
    $("body").on("click", "#btnAdd", function () {
        //Reference the Name and Country TextBoxes.
        var txtName = $("#txtName");
        var txtCountry = $("#txtCountry");

        //Get the reference of the Table's TBODY element.
        var tBody = $("#tblCustomers > TBODY")[0];

        //Add Row.
        var row = tBody.insertRow(-1);

        //Add Name cell.
        var cell = $(row.insertCell(-1));
        cell.html(txtName.val());

        //Add Country cell.
        cell = $(row.insertCell(-1));
        cell.html(txtCountry.val());

        //Add Button cell.
        cell = $(row.insertCell(-1));
        var btnRemove = $("<input />");
        btnRemove.attr("type", "button");
        btnRemove.attr("onclick", "Remove(this);");
        btnRemove.val("Remove");
        cell.append(btnRemove);

        //Clear the TextBoxes.
        txtName.val("");
        txtCountry.val("");
    });

    function Remove(button) {
        //Determine the reference of the Row using the Button.
        var row = $(button).closest("TR");
        var name = $("TD", row).eq(0).html();
        if (confirm("Do you want to delete: " + name)) {
            //Get the reference of the Table.
            var table = $("#tblCustomers")[0];

            //Delete the Table row using it's Index.
            table.deleteRow(row[0].rowIndex);
        }
    };

    $("body").on("click", "#btnSave", function () {
        //Loop through the Table rows and build a JSON array.
        var customers = new Array();
        $("#tblCustomers TBODY TR").each(function () {
            var row = $(this);
            var customer = {};
            customer.Name = row.find("TD").eq(0).html();
            customer.Country = row.find("TD").eq(1).html();
            customers.push(customer);
        });

        //Send the JSON array to Controller using AJAX.
        $.ajax({
            type: "POST",
            url: "/Home/InsertCustomers",
            data: JSON.stringify(customers),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                alert(r + " record(s) inserted.");
            }
        });
    });
</script>

控制器:

    // GET: Home
    public ActionResult Index()
    {
        CustomersEntities entities = new CustomersEntities();
        return View(entities.Customers);
    }

    public JsonResult InsertCustomers(List<Customer> customers)
    {
        using (CustomersEntities entities = new CustomersEntities())
        {
            //Truncate Table to delete all old records.
            entities.Database.ExecuteSqlCommand("TRUNCATE TABLE [Customers]");

            //Check for NULL.
            if (customers == null)
            {
                customers = new List<Customer>();
            }

            //Loop and insert records.
            foreach (Customer customer in customers)
            {
                entities.Customers.Add(customer);
            }
            int insertedRecords = entities.SaveChanges();
            return Json(insertedRecords);
        }
    }

型号

 public partial class Customer
{
    public int CustomerId { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
}

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-3 asp.net-ajax


    【解决方案1】:

    要添加多个记录,您需要为每个文本框添加不同的 ID。您可以通过 jquery 和 javascript 添加多个文本框,最多 10 条记录(您可以用 Jquery 代码中的任意数字替换 10)。这是一个例子。

    $(document).ready(function () {
    
                $("#addButton").click(function () {
                    if( ($('.form-horizontal .control-group').length+1) > 10) {
                        alert("Only 10 control-group allowed");
                        return false;
                    }
                    var id = ($('.form-horizontal .control-group').length + 1).toString();
                    $('.form-horizontal').append('<input type="text" id="txtName' + id + '" placeholder="Name">&nbsp<input type="text" id="txtCountry' + id + '" placeholder="Country"></div></div></div>');
                });
    
    
            });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="form-horizontal">
            <div class="control-group">
              <td><input type="text" id="txtName" placeholder="Name"/></td>
                <td><input type="text" id="txtCountry" placeholder="Country" /></td>
            </div>
        </div>
        <input type='button' value='Add Record' id='addButton' />
        

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      相关资源
      最近更新 更多