locked
Dynamically add rows in MVC RRS feed

  • Question

  • User-199788946 posted

    I want to dynamically add and delete row when plus and delete button in clicked also drop down value also added dynamically in each row: 

    https://drive.google.com/file/d/1xGK9HBeLAUAVgTUt_sP_VyXtBKywtprG/view?usp=sharing

    I have write following code couldn't work:

            [HttpPost]
    
            public ActionResult CreateExpReq(string any = "")
            {
                IList<ProposedExpData> _TableForm = new List<ProposedExpData>();
                using (DBEntities dBEntities=new DBEntities())
                {
                    ViewBag.DAcount = dBEntities.AccountHeads.ToList();
    
                }
    
                //Loop through the forms
                for (int i = 0; i <= Request.Form.Count; i++)
                {
                    var DebitAccount = Request.Form["DebitAccount[" + i + "]"];
                    var Amount = Convert.ToInt32(Request.Form["Amount[" + i + "]"]);
                    var ExpenseDescription = Request.Form["ExpenseDescription[" + i + "]"];
    
                    if (!String.IsNullOrEmpty(DebitAccount))
                    {
                        _TableForm.Add(new ProposedExpData { DebitAccount = DebitAccount, Amount = Amount, ExpenseDescription = ExpenseDescription });
                    }
                }
    
                return View();
            }

    My model:

        public class ProposedExpData
        {
            public int Id { get; set; }
            public string DebitAccount { get; set; }
            public int Amount { get; set; }
            public string ExpenseDescription { get; set; }
        }

    My view:

                        @using (Html.BeginForm())
                        {
                            @Html.ValidationSummary(true)
    
                            <fieldset>
                                <legend>Sample submission</legend>
                                <table id="submissionTable" class="table table-bordered">
                                    <thead>
                                        <tr>
                                            <td>Debit Account</td>
                                            <td>Amount</td>
                                            <td>Expense Description</td>
                                        </tr>
                                    </thead>
    
                                    <tr id="tablerow0">
                                        <td>
                                            <div class="editor-field">
                                                <select id="cars" name="DebitAccount[0]" class="form-control">
                                                    @foreach (var item in ViewBag.DAcount)
                                                    {
                                                        <option value="@item.Description">@item.Description</option>
                                                    }
                                                </select>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="editor-field">
                                                <input class="text-box single-line" name="Amount[0]" type="text" value="" required="required" />
                                            </div>
                                        </td>
                                        <td>
                                            <div class="editor-field">
                                                <input class="text-box single-line" name="ExpenseDescription[0]" type="text" value="" />
                                            </div>
                                        </td>
                                        <td>
                                            <button type="button" class="btn btn-danger" onclick="removeTr(0);">Delete</button>
                                        </td>
                                        <td>
                                        </td>
                                    </tr>
    
                                </table>
                                <p>
                                    <button id="add"><span class="glyphicon glyphicon-plus" style="color:blue"></span></button>
                                </p>
                                <hr />
                            </fieldset>
                        }
    
    
                        <div class="form-group row">
                            <button type="submit" class="btn btn-primary ml-3">Save</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    @section Scripts {
        <script src="~/bundles/jqueryval.js" type="text/javascript">
            var counter = 1;
            $(function () {
                $('#add').click(function () {
                    $('<tr id="tablerow' + counter + '"><td>' +
                        '<input type="text" class="text-box single-line" name="DebitAccount[' + counter + ']" value="" required="required" />' +
                        '</td>' +
                        '<td>' +
                        '<input type="text" class="text-box single-line" name="Amount[' + counter + ']" value="" required="required" />' +
                        '</td>' +
                        '<td>' +
                        '<input type="text" class="text-box single-line" name="ExpenseDescription[' + counter + ']" value="" required="required" />' +
                        '</td>' +
                        '<td>' +
                        '<button type="button" class="btn btn-primary" onclick="removeTr(' + counter + ');">Delete</button>' +
                        '</td>' +
                        '</tr>').appendTo('#submissionTable');
                    counter++;
                    return false;
                });
            });
            function removeTr(index) {
                if (counter > 1) {
                    $('#tablerow' + index).remove();
                    counter--;
                }
                return false;
            }
            
        </script>
        }

    Friday, May 29, 2020 6:21 AM

Answers

  • User1686398519 posted

    Hi,  jameslovemicrosoft

    Your code "<script src =" ~ / bundles / jqueryval.js "type =" text / javascript ">" is wrong, you can change it to "<script src =" ~ / bundles / jqueryval "> < / script><script type = "text / javascript"> ".

    In addition, displaying and adding information should not be in one form.I used modal.

    According to your needs, I have modified the previous example, please refer to it.

    Controller

            [HttpPost]
            public ActionResult CreateExpReqPost()
            {
                for (int i = 0; i <Request.Form.Count/3; i++)
                {
                    ProposedExpData proposedExpData = new ProposedExpData();
                    proposedExpData.DebitAccount = Request.Form["DebitAccount[" + i + "]"];
                    proposedExpData.Amount = Convert.ToInt32(Request.Form["Amount[" + i + "]"]);
                    proposedExpData.ExpenseDescription = Request.Form["ExpenseDescription[" + i + "]"];
                    db.ProposedExpDatas.Add(proposedExpData);
                    db.SaveChanges();
                }
                return RedirectToAction("ListExpReq");
            }

    CreateExpReq

    <fieldset>
        <legend>Sample submission</legend>
    
        <div id="successMessage"></div>
        <p>
            <button id="openModal"><span class="glyphicon glyphicon-plus" style="color:blue"></span></button>
        </p>
        @using (Html.BeginForm("CreateExpReqPost","Home"))
        {
            <table id="showTable" class="table table-bordered">
                <thead>
                    <tr>
                        <td>Debit Account</td>
                        <td>Amount</td>
                        <td>Expense Description</td>
                        <td></td>
                    </tr>
                </thead>
            </table>
            <button type="submit" id="saveBulkData" class="" btn"><span class="glyphicon glyphicon-plus" style="color:blue"></span>Save Bulk Data</button>
        }
        </fieldset>
    
    <div id="AddExpReqModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Sample submission</h4>
                </div>
                <div class="modal-body">
                    <div id="errorMessage">
                    </div>
                    <form id="addform">
                        <fieldset>
                            <table id="submissionTable" class="table table-bordered">
                                <tr>
                                    <td>Debit Account</td>
                                    <td>
                                        <div class="editor-field">
                                            <select id="cars" name="DebitAccount" class="form-control">
                                                @foreach (var item in ViewBag.DAcount)
                                                {
                                                    <option value="@item.Id">@item.Description</option>
                                                }
                                            </select>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td>Amount</td>
                                    <td>
                                        <div class="editor-field">
                                            <input class="text-box single-line" name="Amount" type="text" value="" required="required" />
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td>Expense Description</td>
                                    <td>
                                        <div class="editor-field">
                                            <input class="text-box single-line" name="ExpenseDescription" type="text" value="" />
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </fieldset>
                    </form>
                </div>
                <div class="modal-footer">
                    <button id="add"><span class="glyphicon glyphicon-plus" style="color:blue"></span></button>
                </div>
            </div>
        </div>
    </div>
    @section Scripts {
        <script src="~/bundles/jqueryval"></script>
        <script type="text/javascript">
            $('#openModal').click(function () {
                $("#successMessage").empty();
                $("#AddExpReqModal").modal("show");
            });
            var counter = 0;
            $(function () {
                $('#add').click(function () {
                    if (checkAmount()) {
                        var $tr = $('<tr id="tablerow' + counter + '"></tr>');
                        var $td1 = $('<td><input type="text" class="text-box single-line" name="DebitAccount[' + counter + ']" value="' + $("#addform select option:selected").val() + '" required="required" /></td>');
                        $td1.appendTo($tr);
                        var $td2 = $('<td><input type="text" class="text-box single-line" name="Amount[' + counter + ']" value="' + $("#addform input[name!='Amount']").val() + '" required="required" /></td>');
                        $td2.appendTo($tr);
                        var $td3 = $('<td><input type="text" class="text-box single-line" name="ExpenseDescription[' + counter + ']" value="' + $("#addform input[name!='ExpenseDescription']").val() + '" required="required" /></td>');
                        $td3.appendTo($tr);
                        var $td = $('<td><button type="button" class="btn btn-danger" onclick="removeTr(' + counter + ');">Delete</button></td>');
                        $td.appendTo($tr);
                        $tr.appendTo('#showTable');
                        counter++;
                        $("#AddExpReqModal").modal("toggle");
    
                        $('#AddExpReqModal').on('hidden.bs.modal', function () {
                            $(this).find("input").val('').end();
                        });
                        $('#successMessage').append("<div class='alert alert-success alert-dismissable'><button type ='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button >Success.</div >");
                    }
                });
            });
            function checkAmount() {
                $("errorMessage").empty();
                if ($("#addform input[name!='Amount']").val() == "") {
                    $('#errorMessage').append("<div class='alert alert-danger alert-dismissable'><button type ='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button >The value of Amount cannot be null.</div >");
                    return false;
                } else {
                    return true;
                }
            }
            function removeTr(index) {
                if (counter > 1) {
                    $('#tablerow' + index).remove();
                    counter--;
                }
                return false;
            }
    
        </script>
    }

    Here is the result.

     
    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 1, 2020 6:35 AM

All replies

  • User1686398519 posted

    Hi,  jameslovemicrosoft

    • Based on the code you gave, I found that you just received the data from the front end, and did not store it in the database or return it to the front end.
    • I made an example, please refer to it.
    • This link may be helpful to you, please refer to it.

    Model

    public class AccountHead
        {
            [Key]
            public int Id { get; set; }
            public string Description { get; set; }
        }
        public class ProposedExpData
        {
            [Key]
            public int Id { get; set; }
            public string DebitAccount { get; set; }
            public int Amount { get; set; }
            public string ExpenseDescription { get; set; }
            [NotMapped]
            public SelectList AccountSelectList { get; set; }
        }

    Controller

          public Model1 db = new Model1();
            public ActionResult ListExpReq()
            {
                var proposedExpDataslist = db.ProposedExpDatas.ToList();
                proposedExpDataslist.ForEach(p =>
                {
    //Let the dropdownlist of each row of data display the value you selected p.AccountSelectList= new SelectList(db.AccountHeads, "Id", "Description",p.DebitAccount); }); return View(proposedExpDataslist); } public ActionResult CreateExpReq() { ViewBag.DAcount = new SelectList(db.AccountHeads, "Id", "Description"); return View(); } [HttpPost] public ActionResult CreateExpReq(ProposedExpData proposedExpData) { if (!String.IsNullOrEmpty(proposedExpData.DebitAccount)) { db.ProposedExpDatas.Add(proposedExpData); db.SaveChanges(); } return RedirectToAction("ListExpReq"); } public ActionResult DeleteExpReq(int? Id) { return PartialView("ToDelete"); } [HttpPost,ActionName("DeleteExpReq")] public ActionResult DeleteExpReqConfirm(int? Id) { ProposedExpData proposedExpData = db.ProposedExpDatas.Find(Id); db.ProposedExpDatas.Remove(proposedExpData); db.SaveChanges(); return RedirectToAction("ListExpReq"); }

    ListExpReq

    @model IEnumerable<WebApplication1.Models.ProposedExpData>
    @{
        ViewBag.Title = "ListExpReq";
    }
    
    <h2>ListExpReq</h2>
    <span class="glyphicon glyphicon-plus" style="color:blue"></span>
    @Html.ActionLink("add", "CreateExpReq", new { @class = "btn btn-primary", style = "color:blue" })
    <table id="submissionTable" class="table table-bordered">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.DebitAccount)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Amount)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ExpenseDescription)
            </th>
            <th>
    
            </th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DropDownList("DebitAccount", item.AccountSelectList as SelectList, "Default")
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Amount)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.ExpenseDescription)
                </td>
                <td>
                    @Html.ActionLink("Delete", "DeleteExpReq", new { Id = @item.Id }, new { @class = "btn btn-danger", data_toggle = "modal", data_target = "#DeleteExpReqModal" })
                </td>
            </tr>
        }
    
    </table>
    <div id="DeleteExpReqModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
    
            </div>
        </div>
    </div>
    

    CreateExpReq

    @{
        ViewBag.Title = "CreateExpReq";
    }
    
    <h2>CreateExpReq</h2>
    @model WebApplication1.Models.ProposedExpData
    @using (Html.BeginForm("CreateExpReq"))
    {
        @Html.ValidationSummary(true)
    
        <fieldset>
            <legend>Sample submission</legend>
            <table id="submissionTable" class="table table-bordered">
                <thead>
                    <tr>
                        <td>Debit Account</td>
                        <td>Amount</td>
                        <td>Expense Description</td>
                    </tr>
                </thead>
                <tr id="tablerow0">
                    <td>
                        <div class="editor-field">
                            @Html.DropDownListFor(m=>m.DebitAccount, ViewBag.DAcount as SelectList,"Default", htmlAttributes: new { @class = "form-control" })
                        </div>
                    </td>
                    <td>
                        <div class="editor-field">
                            @Html.TextBoxFor(m=>m.Amount,new { @class = "text-box single-line", required = "required" })
                        </div>
                    </td>
                    <td>
                        <div class="editor-field">
                            @Html.TextBoxFor(m => m.ExpenseDescription, new { @class = "text-box single-line"})
                        </div>
                    </td>
                    <td>
                    </td>
                </tr>
            </table>
            <p>
                <button type="submit" id="add"><span class="glyphicon glyphicon-plus" style="color:blue"></span></button>
            </p>
            <hr />
        </fieldset>
    }
    

    ToDelete

    @using (Html.BeginForm())
    {
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Modal title</h4>
        </div>
        <div class="modal-body">
            Are you sure?
        </div>
        <div class="modal-footer">
            <button type="submit" class="btn btn-primary">YES</button>
        </div>
    }
    

    Here is the result.

     
    Best Regards,

    YihuiSun

    Friday, May 29, 2020 12:08 PM
  • User-199788946 posted

    Thank you for your reply,

    I want to add multiple rows form before submitting data to database I don't think for this I need to add database.

    lets say: first shown 1 row when I press add 

    two rows add in same form element.

    like I want to insert multiple rows value to database.

    something like  following images in my form:

    https://drive.google.com/file/d/1DAEAlOEbNbtSGLRIJ_MdPYzAU9ADjUWL/view?usp=sharing 

    Friday, May 29, 2020 1:19 PM
  • User-2054057000 posted

    like I want to insert multiple rows value to database.

    You can create your own logic to insert multiple rows. I would call a stored procedure in SQL which will do this work. The logic would be your own for it.

    Monday, June 1, 2020 6:04 AM
  • User1686398519 posted

    Hi,  jameslovemicrosoft

    Your code "<script src =" ~ / bundles / jqueryval.js "type =" text / javascript ">" is wrong, you can change it to "<script src =" ~ / bundles / jqueryval "> < / script><script type = "text / javascript"> ".

    In addition, displaying and adding information should not be in one form.I used modal.

    According to your needs, I have modified the previous example, please refer to it.

    Controller

            [HttpPost]
            public ActionResult CreateExpReqPost()
            {
                for (int i = 0; i <Request.Form.Count/3; i++)
                {
                    ProposedExpData proposedExpData = new ProposedExpData();
                    proposedExpData.DebitAccount = Request.Form["DebitAccount[" + i + "]"];
                    proposedExpData.Amount = Convert.ToInt32(Request.Form["Amount[" + i + "]"]);
                    proposedExpData.ExpenseDescription = Request.Form["ExpenseDescription[" + i + "]"];
                    db.ProposedExpDatas.Add(proposedExpData);
                    db.SaveChanges();
                }
                return RedirectToAction("ListExpReq");
            }

    CreateExpReq

    <fieldset>
        <legend>Sample submission</legend>
    
        <div id="successMessage"></div>
        <p>
            <button id="openModal"><span class="glyphicon glyphicon-plus" style="color:blue"></span></button>
        </p>
        @using (Html.BeginForm("CreateExpReqPost","Home"))
        {
            <table id="showTable" class="table table-bordered">
                <thead>
                    <tr>
                        <td>Debit Account</td>
                        <td>Amount</td>
                        <td>Expense Description</td>
                        <td></td>
                    </tr>
                </thead>
            </table>
            <button type="submit" id="saveBulkData" class="" btn"><span class="glyphicon glyphicon-plus" style="color:blue"></span>Save Bulk Data</button>
        }
        </fieldset>
    
    <div id="AddExpReqModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Sample submission</h4>
                </div>
                <div class="modal-body">
                    <div id="errorMessage">
                    </div>
                    <form id="addform">
                        <fieldset>
                            <table id="submissionTable" class="table table-bordered">
                                <tr>
                                    <td>Debit Account</td>
                                    <td>
                                        <div class="editor-field">
                                            <select id="cars" name="DebitAccount" class="form-control">
                                                @foreach (var item in ViewBag.DAcount)
                                                {
                                                    <option value="@item.Id">@item.Description</option>
                                                }
                                            </select>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td>Amount</td>
                                    <td>
                                        <div class="editor-field">
                                            <input class="text-box single-line" name="Amount" type="text" value="" required="required" />
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td>Expense Description</td>
                                    <td>
                                        <div class="editor-field">
                                            <input class="text-box single-line" name="ExpenseDescription" type="text" value="" />
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </fieldset>
                    </form>
                </div>
                <div class="modal-footer">
                    <button id="add"><span class="glyphicon glyphicon-plus" style="color:blue"></span></button>
                </div>
            </div>
        </div>
    </div>
    @section Scripts {
        <script src="~/bundles/jqueryval"></script>
        <script type="text/javascript">
            $('#openModal').click(function () {
                $("#successMessage").empty();
                $("#AddExpReqModal").modal("show");
            });
            var counter = 0;
            $(function () {
                $('#add').click(function () {
                    if (checkAmount()) {
                        var $tr = $('<tr id="tablerow' + counter + '"></tr>');
                        var $td1 = $('<td><input type="text" class="text-box single-line" name="DebitAccount[' + counter + ']" value="' + $("#addform select option:selected").val() + '" required="required" /></td>');
                        $td1.appendTo($tr);
                        var $td2 = $('<td><input type="text" class="text-box single-line" name="Amount[' + counter + ']" value="' + $("#addform input[name!='Amount']").val() + '" required="required" /></td>');
                        $td2.appendTo($tr);
                        var $td3 = $('<td><input type="text" class="text-box single-line" name="ExpenseDescription[' + counter + ']" value="' + $("#addform input[name!='ExpenseDescription']").val() + '" required="required" /></td>');
                        $td3.appendTo($tr);
                        var $td = $('<td><button type="button" class="btn btn-danger" onclick="removeTr(' + counter + ');">Delete</button></td>');
                        $td.appendTo($tr);
                        $tr.appendTo('#showTable');
                        counter++;
                        $("#AddExpReqModal").modal("toggle");
    
                        $('#AddExpReqModal').on('hidden.bs.modal', function () {
                            $(this).find("input").val('').end();
                        });
                        $('#successMessage').append("<div class='alert alert-success alert-dismissable'><button type ='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button >Success.</div >");
                    }
                });
            });
            function checkAmount() {
                $("errorMessage").empty();
                if ($("#addform input[name!='Amount']").val() == "") {
                    $('#errorMessage').append("<div class='alert alert-danger alert-dismissable'><button type ='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button >The value of Amount cannot be null.</div >");
                    return false;
                } else {
                    return true;
                }
            }
            function removeTr(index) {
                if (counter > 1) {
                    $('#tablerow' + index).remove();
                    counter--;
                }
                return false;
            }
    
        </script>
    }

    Here is the result.

     
    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 1, 2020 6:35 AM