简体   繁体   中英

ASP.NET Core - Multiple Row Insert with Dropdown List

Sorry if this question has been asked multiple times already but I've looked everywhere and I'm at a loss as of what to do.

I'm trying to insert multiple records with two text fields and a dropdown, when all the inputs are text fields, it works fine, I can add multiple rows and submit them to my database, but as soon as I add the dropdown, it won't allow me to add another row:

Code - controller:

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly FIDatabaseContext _context;

    public HomeController(FIDatabaseContext context, ILogger<HomeController> logger)
    {
        _logger = logger;
        _context = context;
    }

    public ActionResult BulkData()
    {
        List<ContactInfoNew> ci = new List<ContactInfoNew> { new ContactInfoNew { ContactName = "", ContactNo = "" } };
        ViewBag.New = new SelectList(_context.TestTables.OrderByDescending(c => c.TestId).ToList(), "TestId", "TestId");

        return View(ci);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult BulkData(List<ContactInfoNew> ci)
    {
        if (ModelState.IsValid)
        {
            using (FIDatabaseContext dc = new FIDatabaseContext())
            {
                foreach (var i in ci)
                {
                    dc.ContactInfoNews.Add(i);
                }

                dc.SaveChanges();

                ViewBag.Message = "Data successfully saved!";
                
                ViewBag.New = new SelectList(_context.TestTables.OrderByDescending(c => c.TestId).ToList(), "TestId", "TestId");

                ModelState.Clear();
                ci = new List<ContactInfoNew> { new ContactInfoNew { ContactName = "", ContactNo = "" } };
            }
        }

        return View(ci);
    }

My view:

@model List<EFCore.Models.ContactInfoNew>

@{
    ViewBag.Title = "Insert Bulk Data";
}
                    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/json2/20160511/json2.js" integrity="sha512-h3RrO+eudpiPUYFkwORXD2ppuy9jOXQ+MzVEIo7k+OuA7y9Ze5jsQ5WN/ZSgI+ZSIngT6pDSaqpgmnam2HPe1g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<div style="width:700px; padding:5px; background-color:white;">
    using (Html.BeginForm("BulkData","Home", FormMethod.Post))
    {
        Html.AntiForgeryToken()
        Html.ValidationSummary(true)
        
        if (ViewBag.Message != null)
        {
            <div style="border:solid 1px green">
                @ViewBag.Message
            </div>
        }
        
        <div><a href="#" id="addNew">Add New</a></div>
        <table id="dataTable" border="0" cellpadding="0" cellspacing="0">
            <tr>
                <th>Contact Name</th>
                <th>Contact No</th>
                <th>Test</th>
                <th></th>
            </tr>
            @if (Model != null && Model.Count > 0)
            {
                int j = 0;
                foreach (var i in Model)
                {
                    <tr style="border:1px solid black">
                       
                        <td>
                            <div id="contactname">
                            @Html.TextBoxFor(a=>a[j].ContactName)
                            </div>
                        </td>

                        <td>
                            <div id="contactno">
                            @Html.TextBoxFor(a=>a[j].ContactNo)
                            </div>
                        </td>

                        <td>
                            <div id="testidreal">
                            @Html.DropDownListFor(a=>a[j].TestId, (IEnumerable<SelectListItem>)ViewBag.New)
                            </div>
                        </td>


                        <td>
                            @if (j > 0)
                            {
                                <a href="#" class="remove">Remove</a>
                            }
                        </td>
                    </tr>
                    j++;
                }
            }
        </table>
        <input type="submit" value="Save Bulk Data" />
    }
</div>

<script language="javascript">
        $(document).ready(function () {
 
            //1. Add new row
            $("#addNew").click(function (e) {
                e.preventDefault();
                var $tableBody = $("#dataTable");
                var $trLast = $tableBody.find("tr:last");
                var $trNew = $trLast.clone();
 
                var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);
                $trNew.find("td:last").html('<a href="#" class="remove">Remove</a>');
                $.each($trNew.find(':input'), function (i, val) {
                    // Replaced Name
                    var oldN = $(this).attr('name');
                    var newN = oldN.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');
                    $(this).attr('name', newN);

                    //Replaced value
                    var type = $(this).attr('type');
                    if (type.toLowerCase() == "text") {
                        $(this).attr('value', '');

                    }
 
                    // If you have another Type then replace with default value
                    $(this).removeClass("input-validation-error");
 
                });
                $trLast.after($trNew);
 
                // Re-assign Validation 
                var form = $("form")
                    .removeData("validator")
                    .removeData("unobtrusiveValidation");
                $.validator.unobtrusive.parse(form);
            });
 
            // 2. Remove 
            $('a.remove').on("click", function (e) {
                e.preventDefault();
                $(this).parent().parent().remove();
            });
 
        });
    </script>
}

If anyone can help me, that'd be brilliant,

Thank you!

SOLVED : I removed this portion of code -

 //Replaced value
                var type = $(this).attr('type');
                if (type.toLowerCase() == "text") {
                    $(this).attr('value', '');

                }

                // If you have another Type then replace with default value
                $(this).removeClass("input-validation-error");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM