locked
Dynamically add partial views to the table for uploading files RRS feed

  • Question

  • User-1244692504 posted

    Hi everyone. 

    Please I have a challenge in adding partial modal views to Table to upload files.

    My Model:

     	public class DocumentAttachment
            {
                public string PolicyRefCode { get; set; }
                public string PolicyDocumentPath { get; set; }
    	    public string ModifiedBy { get; set; }
                public Int64 RowVersionNo2 { get; set; }
                [IdentityPrimaryKey()]
                public int RecordID { get; set; }
            }
    
    	public class Underwriting_PolicyFile
            {
                public string PolicyRefCode { get; set; }
                public string Interest { get; set; }
                public DateTime TransDate { get; set; }
    	}
    
    
        public class ClientPolicyViewModel
        {
            public Brokerage.Model.Underwriting_PolicyFile Underwriting_PolicyFile { get; set;}
            public List<DocumentAttachment> DocumentAttachment { get; set; }
        }
    

    My Controller:

    	HTTPGET
     	public ActionResult EditClientPolicy(string id, string actionType, string transCode, string debitNoteNo, decimal? renewalPremium, decimal? additionalPremium) 
            {
                ViewBag.OperationName = string.Empty;
    		
    	     entityToEdit.DocumentAttachment.Add(new DocumentAttachment() { PolicyRefCode = " ", PolicyDocumentPath = " " });
    
     	   return View(entityToEdit);
            }

    Parent View

    Main View
    @using Brokerage.Utility;
    @using Brokerage.Web.Common;
    @model Brokerage.Model.ClientPolicyViewModel
    
     @using (Html.BeginForm("EditClientPolicy", "Underwriting", FormMethod.Post, new { id = "clientPolicyForm", enctype="multipart/form-data"}))
    
     	 <div class="row">
                <div class="col-md-12 col-sm-12 col-xs-12">
                    <div class="form-group">
                        @Html.LabelFor(model => model.Underwriting_PolicyFile.PolicyRefCode, "Policy_Ref No", htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.Underwriting_PolicyFile.PolicyRefCode, new { id = "Underwriting_PolicyFile.PolicyRefCode", htmlAttributes = new { @class = "form-control input-sm", @readonly = true } })
                            @Html.ValidationMessageFor(model => model.Underwriting_PolicyFile.PolicyRefCode, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </div>
                <div class="col-md-12 col-sm-12 col-xs-12">
                    <div class="form-group">
                        @Html.LabelFor(model => model.Underwriting_PolicyFile.ClientCode, "Client Name", htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.Hidden("Underwriting_PolicyFile.ClientCode", Model.Underwriting_PolicyFile.ClientCode)
                            @Html.DropDownList("Underwriting_PolicyFile.ClientCode1", new SelectList(Html.GeneralClientCodeDropDownList(), "ClientCode", "Name", Model.Underwriting_PolicyFile.ClientCode), new { id = "Underwriting_PolicyFile.ClientCode1", @class = "form-control input-sm", @disabled = "disabled" })
                            @Html.ValidationMessageFor(model => model.Underwriting_PolicyFile.ClientCode, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </div>
    
         if (ViewBag.OperationName == "Attachment")
          {
          <a href="#showAttachmentDialog" class="btn btn-primary" title="Attach Document To Policy" data-toggle="modal" data-id="">Attach Document(s)</a>
         }
         <input type="submit" name="actionType" value= "@ViewBag.ActionType" class="btn btn-primary" style="float:right" />
    

    Modal View:

            <div class="row">
                <div class="col-md-12 col-sm-8 col-xs-12 col-xs-offset-0">
                    <div id="showAttachmentDialog" tabindex="-1" role="dialog" aria-labelledby="showDialogLabel" aria-hidden="true" class="modal fade">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                                    <h4 class="modal-title" id="showDialogLabel">Document Attachment</h4>
                                </div>
                                <div class="modal-body">
                                    <hr />
                                    <input type="submit" class="btn btn-primary" value="Add Attachment" onclick="addRow('requestInsurerItems'); return false;" />
                                    <input type="submit" class="btn btn-primary" value="Remove Attachment" onclick="    removeRow('requestInsurerItems'); return false;" />
    
                                    <hr />
                                    <div class="table-responsive">
                                        <table id="requestInsurerItems" class="table table-bordered table-striped table-hover" cellspacing="0">
                                            <thead style=" background-color:#89006e !important; color:#fff;font-weight:bold;">
                                                <tr>
                                                    <td>PolicyRefCode</td>
                                                    <td>PolicyDocument</td>
                                                </tr>
                                            </thead>
                                            @{if (!string.IsNullOrEmpty(Model.Underwriting_PolicyFile.PolicyDocumentPath))
                                            {
                                                var prefx4 = "DocumentAttachment";
                                                var prefx6 = prefx4 + ".index";
                                                for (var i = 1; i <= Model.DocumentAttachment.Count; i++)
                                                {
                                                    var itemIndex3 = string.Format("X{0}", i);
                                                    var n7 = string.Format("{1}[X{0}].PolicyRefCode", i, prefx4);
                                                    var n8 = string.Format("{1}[X{0}].PolicyDocument", i, prefx4);
    
                                                    <tr>
                                                        <td>
                                                            <input type="file" name="@prefx6" value="@itemIndex3" />
                                                            @Html.TextBox(n7, Model.DocumentAttachment[i - 1].PolicyRefCode, new { id = n7, @class = "form-control input-sm", @style = "width: 100px;" })
                                                            @Html.ValidationMessage(n7, "", new { @class = "text-danger" })
                                                        </td>
                                                        <td>
                                                            @Html.TextBox(n8, Model.DocumentAttachment[i - 1].PolicyDocumentPath, new { id = n8, @class = "form-control input-sm", @style = "width: 350px;" })
                                                            @Html.ValidationMessage(n8, "", new { @class = "text-danger" })
                                                        </td>
    
                                                    </tr>
                                                }
                                            }
                                            else
                                            {
                                                int c = 1;
                                                foreach (var module in Model.DocumentAttachment)
                                                {
                                                    Html.RenderPartial("DocumentAttachmentEditor", module, new ViewDataDictionary(ViewData) {
    		                                             {"prefix", "DocumentAttachment"}, {"itemIndex", "X" + c}
    		                                             });
                                                    c = c + 1;
                                                }
                                            }
                                            }
                                        </table>
                                    </div>
                                </div>
    
                                <div class="modal-footer" style="background:#e8c8d8; border-radius:8px">
    
                                    <button type="button" class="btn btn-primary" data-dismiss="modal">Next</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

    Partial View

    @using Brokerage.Utility;
    @model Brokerage.Model.DocumentAttachment
    <tr>
        @{var prefx = @ViewData["prefix"] + ".index";}
        @{var itIndex = @ViewData["itemIndex"];}
    
        @{var fieldPrefix = string.Format("{0}[{1}].", ViewData["prefix"], ViewData["itemIndex"]); }
        <td>
            <input type="file" name="@prefx" value="@itIndex" />
            @Html.Editor(fieldPrefix + "PolicyRefCode", new { htmlAttributes = new { id = fieldPrefix + "PolicyRefCode", @class = "form-control input-sm", @style = "width: 100px;" } })
            @Html.ValidationMessage(fieldPrefix + "PolicyRefCode")
        </td>
        <td>
            @Html.Editor(fieldPrefix + "PolicyDocumentPath", new { htmlAttributes = new { id = fieldPrefix + "PolicyDocumentPath", @class = "form-control input-sm", @style = "width: 100px;", type = "file", Name = "PolicyDocument[" + @prefx + "]" } })
            @Html.ValidationMessage(fieldPrefix + "PolicyDocumentPath")
        </td>
    </tr>
    

    Controller HPPTPOST

     public ActionResult EditClientPolicy(ClientPolicyViewModel model,  HttpPostedFileBase PolicyDocument)
            {
                ViewBag.OperationName = operationName;
                ViewBag.ActionType = actionType;
    
                            if (transCode == Constants.TransactionCodes.FirstPremium)
                            {
                                if (PolicyDocument != null)
                                {
                                    fileName = Path.GetFileNameWithoutExtension(PolicyDocument.FileName); // Get the filename
                                    extension = Path.GetExtension(PolicyDocument.FileName);
    
                                    fileExt = Path.GetExtension(PolicyDocument.FileName).Substring(1);
    
                                    fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;  //Create a unique signature file name to avoid duplication.
    
    model.Underwriting_PolicyFile.PolicyDocumentPath = "~/PDFReport/Documents/" + fileName; // save the relative file path PolicyDocument.SaveAs(Path.Combine(Server.MapPath("~/PDFReport/Documents/"), fileName)); //save the full path to HttpPostedFileBase File. //path = Path.Combine(Server.MapPath("~/PDFReport/Documents/"), Path.GetFileName(files[i].FileName)); ViewBag.FileStatus = "File uploaded successfully. {path}"; } } actionType = "Done"; //ViewBag.TransCode = Constants.TransactionCodes.RenewalPemium; ViewBag.TransCode = transCode; return RedirectToAction("EditClientPolicy", new { id = model.Underwriting_PolicyFile.PolicyRefCode, actionType = actionType, transCode = ViewBag.TransCode }); } }

    JavaScript

    function addRow(tableID) {
            var table = document.getElementById(tableID);
            //var rowZeroId = table.rows[0].id;
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
            row.id = "X" + rowCount;
            var colCount = table.rows[1].cells.length;
    
            for (var i = 0; i < colCount; i++) {
    
                var newcell = row.insertCell(i);
                newcell.innerHTML = table.rows[1].cells[i].innerHTML.replace(/X1/g, row.id);
                switch (newcell.childNodes[0].type) {
                    case "text":
                        newcell.childNodes[0].value = "";
                        break;
                    case "checkbox":
                        newcell.childNodes[0].checked = false;
                        break;
                    case "select-one":
                        newcell.childNodes[0].selectedIndex = 0;
                        break;
                    case "hidden":
                        newcell.childNodes[0].value = "";
                        break;
                }
            }
        }
    
    
       function removeRow(tableID) {
            var tbl = document.getElementById(tableID);
            var lastRow = tbl.rows.length;
            if (lastRow > 2) tbl.deleteRow(lastRow - 1);
        }

    The Addrow() method in JavaScript is not working.

    I want the system to increase the table row by 1 when it is clicked so that the user can manage the number of attachment he wanted to do per time.

    I don't want to use Array[] definition, please. I want the row to be incremented by one row per attachment.

    Your urgent attention will be greatly appreciated.

    Tuesday, August 11, 2020 4:32 PM

Answers

  • User-1330468790 posted

    Hi Lawrence_Ajayi,

     

    I hope you to check the  ‘colCount’ in functioaddRow(),maybe the colCount is null.If the table.rows[1] dose not have data. then the variable 'colCount ' will be 0, that way, the following codes will not have chance to add even one row for the table.

    The solution is to check the variable 'colCount'. If colCount equals to 0, then you have to manually add one row for the table. Otherwise, you could use your orginal codes to copy the previous row's format.

     

    You could refer to below codes to modify your codes.

    <script>
    
        function addRow(tableID) {
    
            var table = document.getElementById(tableID);
    
            var rowCount = table.rows.length;
    
            var row = table.insertRow(rowCount);
    
     
    
            row.id = "X" + rowCount;
    
            var colCount = table.rows[1].cells.length;
    
            if (colCount != 0) {
    
                for (var i = 0; i < colCount; i++) {
    
                    var newcell = row.insertCell(i);
    
                    newcell.innerHTML = table.rows[1].cells[i].innerHTML.replace(/X1/g, row.id); 
    
                    switch (newcell.childNodes[0].type) {
    
                        case "text":
    
                            newcell.childNodes[0].value = "";
    
                            break;
    
                        case "checkbox":
    
                            newcell.childNodes[0].checked = false;
    
                            break;
    
                        case "select-one":
    
                            newcell.childNodes[0].selectedIndex = 0;
    
                            break;
    
                        case "hidden":
    
                            newcell.childNodes[0].value = "";
    
                            break;
    
                    }
    
                }
    
            } else
    
            {
    
                var cell = row.insertCell(0);
    
                var element = document.createElement("input");
    
                element.type = "text";
    
                element.name = "txtbox[]";
    
                cell.appendChild(element);
    
     
    
                var cell2 = row.insertCell(1);
    
                var element2 = document.createElement("input");
    
                element2.type = "file";
    
                element2.name = "filebox[]";
    
                cell2.appendChild(element2);
    
     
    
            }
    
        }
    
    </script>v

    Demo:

     

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 12, 2020 9:23 AM
  • User-1330468790 posted

    Hi Lawrence_Ajayi,

     

    The HttpPostedFileBase PolicyDocument pass from the modal view is returning null to the Controller

    You should check the name of the text box which is defined as file type. It should be "PolicyDocument", not "PolicyDocument[" + i + "]".

     

    Java script deleteRow() method is shown below.

    The user should not be able to delete all records. It must remain 1 record. The error message must be triggered if the user attempts to delete all the records. The error message shown below is not working perfectly.

    You should check the  variable ‘rowCount’ value in the function deleteRow().The error message didn’t work is caused by the variable ‘rowCount’.It should be refreshed after each deletion.

    If the rowCount didn’t refresh,then you delete to only the table title left,it  will give the Error Error "TypeError: Cannot read property 'checked' of null".Because the  variable ’c’ won’t be acquired.

    You could refer to below codes to modify yours:

    function deleteRow(tableID) {
    
            try {
    
                var table = document.getElementById(tableID);
    
                var rowCount = table.rows.length;
    
                for (var i = 1; i < rowCount; i++) {
    
                    var row = table.rows[i];
    
                    var c = row.cells[2].childNodes[0];
    
                    if (c.checked)
    
                    {
    
                        if (rowCount <= 2) {
    
                            alert("Cannot delete all the rows.");
    
                            break;
    
                        }
    
                        else {
    
                            table.deleteRow(i);
    
                            rowCount--;
    
                        }
    
                    }
    
     
    
                }
    
            } catch (e) {
    
                BootstrapDialog.alert(e);
    
            }
    
        }

     

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 13, 2020 9:44 AM
  • User-1244692504 posted

    Thank you all. I have found the answer to it

     for(var i =1; i <= model.Underwriting_PolicyFile.DocumentAttachment.Count; i++){

    }

    should have been coded as below
    for(var i = 0; i < model.Underwriting_PolicyFile.DocumentAttachment.Count; i++){

    }


    i have forgotten that the index begins from 0 and not 1
    and i must be less < than the total count for the error to go.
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, August 14, 2020 4:42 PM

All replies

  • User-474980206 posted

    what does  not work mean? the click event not working? the row not showing up? the id's not correct? the post back not work?

    when you use the browsers debugger do you get errors?

    also in the line:

                                   <input type="file" name="@prefx6" value="@itemIndex3" />
                             

     you do realize that the value is not settable for type="file".

    Tuesday, August 11, 2020 6:01 PM
  • User-1330468790 posted

    Hi Lawrence_Ajayi,

     

    I hope you to check the  ‘colCount’ in functioaddRow(),maybe the colCount is null.If the table.rows[1] dose not have data. then the variable 'colCount ' will be 0, that way, the following codes will not have chance to add even one row for the table.

    The solution is to check the variable 'colCount'. If colCount equals to 0, then you have to manually add one row for the table. Otherwise, you could use your orginal codes to copy the previous row's format.

     

    You could refer to below codes to modify your codes.

    <script>
    
        function addRow(tableID) {
    
            var table = document.getElementById(tableID);
    
            var rowCount = table.rows.length;
    
            var row = table.insertRow(rowCount);
    
     
    
            row.id = "X" + rowCount;
    
            var colCount = table.rows[1].cells.length;
    
            if (colCount != 0) {
    
                for (var i = 0; i < colCount; i++) {
    
                    var newcell = row.insertCell(i);
    
                    newcell.innerHTML = table.rows[1].cells[i].innerHTML.replace(/X1/g, row.id); 
    
                    switch (newcell.childNodes[0].type) {
    
                        case "text":
    
                            newcell.childNodes[0].value = "";
    
                            break;
    
                        case "checkbox":
    
                            newcell.childNodes[0].checked = false;
    
                            break;
    
                        case "select-one":
    
                            newcell.childNodes[0].selectedIndex = 0;
    
                            break;
    
                        case "hidden":
    
                            newcell.childNodes[0].value = "";
    
                            break;
    
                    }
    
                }
    
            } else
    
            {
    
                var cell = row.insertCell(0);
    
                var element = document.createElement("input");
    
                element.type = "text";
    
                element.name = "txtbox[]";
    
                cell.appendChild(element);
    
     
    
                var cell2 = row.insertCell(1);
    
                var element2 = document.createElement("input");
    
                element2.type = "file";
    
                element2.name = "filebox[]";
    
                cell2.appendChild(element2);
    
     
    
            }
    
        }
    
    </script>v

    Demo:

     

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 12, 2020 9:23 AM
  • User-1244692504 posted

    Thank you so much, Sean, for your time. The addRow() method is working now.

    However,

    The HttpPostedFileBase PolicyDocument pass from the modal view is returning null to the Controller

    The controller is shown below

            [HttpPost]
            public ActionResult EditClientPolicy(ClientPolicyViewModel model, HttpPostedFileBase PolicyDocument)
            {
                       
                              if (PolicyDocument != null)
                                {
    
                                    fileName = Path.GetFileNameWithoutExtension(PolicyDocument.FileName); // Get the filename
                                    extension = Path.GetExtension(PolicyDocument.FileName);
    
    
                                    fileExt = Path.GetExtension(PolicyDocument.FileName).Substring(1);
    
    
                                    fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;  //Create a unique signature file name to avoid duplication.
    
                                    model.Underwriting_PolicyFile.PolicyDocumentPath = "~/PDFReport/Documents/" + fileName; // save the relative file path
                                    PolicyDocument.SaveAs(Path.Combine(Server.MapPath("~/PDFReport/Documents/"), fileName)); //save the full path to HttpPostedFileBase File.
    
                                  
                                    ViewBag.FileStatus = "File uploaded successfully. {path}";
                                }
    
                        actionType = "Done";
                        ViewBag.TransCode = transCode;
                        return RedirectToAction("EditClientPolicy", new { id = model.Underwriting_PolicyFile.PolicyRefCode });
                    }
                }

    modal view

                                                            <div class="col-md-10">
                                                                @Html.TextBox(n9, Model.DocumentAttachment[i-1].PolicyDocumentPath, new { @class = "form-control input-sm", @style = "width: 500px;", type = "file", Name = "PolicyDocument[" + i + "]" })
                                                            </div>   
      

    Again: I added another method deleteRow() meant to delete the table rows Dynamically by selecting a checkbox. isDeleteCheckbox was added to the model as shown below

     public class DocumentAttachment
            {
                public string PolicyRefCode { get; set; }
                public string PolicyDocumentPath { get; set; }
                public string CertificatePath { get; set; }
                public string EndorsementPath { get; set; }
                public string ModifiedBy { get; set; }
                public Int64 RowVersionNo2 { get; set; }
                [IdentityPrimaryKey()]
                public int RecordID { get; set; }
                public bool isDeletedCheckBox { get; set; }
            }

    and the partial view was modified to include the isDeletedcheckbox property

    Modal view:

     @*Policy distribution*@
            <div class="row">
                <div class="col-md-12 col-sm-8 col-xs-12 col-xs-offset-0">
                    <div id="showAttachmentDialog" tabindex="-1" role="dialog" aria-labelledby="showDialogLabel" aria-hidden="true" class="modal fade">
                        <div class="modal-dialog" style="height:50vh; max-height:50vh; width:100vh; max-width:100vh; overflow-y: initial !important">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                                    <h4 class="modal-title" id="showDialogLabel">Document Attachment</h4>
                                </div>
                                <div class="modal-body">
                                    <hr />
                                    <input type="submit" class="btn btn-primary" value="Add Attachment" onclick="addRow('requestAttachmentItems'); return false;" />
                                    <input type="submit" class="btn btn-primary" value="Remove Attachment" onclick="    removeRow('requestAttachmentItems'); return false;" />
                                    <input type="submit" class="btn btn-primary" value="Delete" onclick="deleteRow('requestAttachmentItems'); return false;" />
    
                                    <hr />
                                    <div class="table-responsive">
                                        <table id="requestAttachmentItems" class="table table-bordered table-striped table-hover" cellspacing="0">
                                            <thead style=" background-color:#89006e !important; color:#fff;font-weight:bold;">
                                                <tr>
                                                    <td>
                                                        <div style="background-color:#89006e !important; color:#fff;font-weight:bold; text-align:center" class="btn btn-primary btn-info">
                                                            <strong></strong><span class="glyphicon glyphicon-remove-sign center-block"></span>
                                                        </div>
                                                    </td>
                                                    <td>PolicyRefCode</td>
                                                    <td>PolicyDocument</td>
                                                </tr>
                                            </thead>
                                            @{if (!string.IsNullOrEmpty(Model.Underwriting_PolicyFile.PolicyRefCode))
                                            {
                                                var prefx4 = "DocumentAttachment";
                                                var prefx6 = prefx4 + ".index";
                                                for (var i = 1; i <= Model.DocumentAttachment.Count; i++)
                                                {
                                                    var itemIndex3 = string.Format("X{0}", i);
    
                                                    var n7 = string.Format("{1}[X{0}].isDeletedCheckBox", i, prefx4);
                                                    var n8 = string.Format("{1}[X{0}].PolicyRefCode", i, prefx4);
                                                    var n9 = string.Format("{1}[X{0}].PolicyDocument", i, prefx4);
                                                    <tr>
                                                        <td>
                                                            <input type="Hidden" name="@prefx6" value="@itemIndex3" />
                                                            <div class="form-group">
                                                                @Html.CheckBox(n7, Model.DocumentAttachment[i - 1].isDeletedCheckBox, new { id = n7, @class = "form-control input-sm", @style = "width: 50px;" })
                                                                @Html.ValidationMessage(n7, "", new { @class = "text-danger" })
                                                             </div>
                                                        </td>
                                                        <td>
                                                            @Html.TextBox(n8, Model.DocumentAttachment[i - 1].PolicyRefCode, new { id = n8, @class = "form-control input-sm", @style = "width: 150px;", @readonly=true })
                                                            @Html.ValidationMessage(n8, "", new { @class = "text-danger" })
                                                        </td>
                                                        <td>
                                                            <div class="col-md-10">
                                                                <iframe src="@Url.Content(Model.DocumentAttachment[i-1].PolicyDocumentPath)" width="100" height="70"></iframe>
                                                                @Html.TextBox(n9, Model.DocumentAttachment[i - 1].PolicyDocumentPath, new { id = n9, @class = "form-control input-sm", @style = "width: 500px;", @readonly=true})
                                                                @Html.TextBox(n9, Model.DocumentAttachment[i-1].PolicyDocumentPath, new { @class = "form-control input-sm", @style = "width: 500px;", type = "file", Name = "PolicyDocument[" + i + "]" })
                                                            </div>   
                                                           
                                                            @Html.ValidationMessage(n9, "", new { @class = "text-danger" })
                                                        </td>
    
                                                    </tr>
                                                }
                                            }
                                            else
                                            {
                                                int c = 1;
                                                foreach (var module in Model.DocumentAttachment)
                                                {
                                                    Html.RenderPartial("DocumentAttachmentEditor", module, new ViewDataDictionary(ViewData) {
    		                                             {"prefix", "DocumentAttachment"}, {"itemIndex", "X" + c}
    		                                             });
                                                    c = c + 1;
                                                }
                                             }
                                            }
                                        </table>
                                    </div>
                                </div>
                                <div class="modal-footer" style="background:#e8c8d8; border-radius:8px">
    
                                    @*<input type="submit" class="btn btn-primary" value="Add New Insurer" onclick="addRow('requestItems');  return false;" />  <input type="submit" class="btn btn-primary" value="Remove Last Insurer" onclick="removeRow('requestItems');  return false;" />*@
                                    <hr />
                                    <input type="submit" class="btn btn-primary" style="float: left" value="Add Attachment" onclick="addRow('requestAttachmentItems'); return false;" />
                                    <input type="submit" class="btn btn-primary" style="float: left" value="Remove Last Attachment" onclick=" removeRow('requestAttachmentItems'); return false;" />
                                    <input type="submit" class="btn btn-primary" style="float: left" value="Delete" onclick="deleteRow('requestAttachmentItems'); return false;" />
                                    <button type="button" class="btn btn-primary" data-dismiss="modal">Next</button>
                                    <hr />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
    

    Partial View:

    @using Brokerage.Utility;
    @model Brokerage.Model.DocumentAttachment
    <tr>
        @{var prefx = @ViewData["prefix"] + ".index";}
        @{var itIndex = @ViewData["itemIndex"];}
    
        @{var fieldPrefix = string.Format("{0}[{1}].", ViewData["prefix"], ViewData["itemIndex"]); }
        <td>
            <input type="Hidden" name="@prefx" value="@itIndex" />
            <div class="form-group">
                @Html.CheckBox(fieldPrefix + "isDeletedCheckBox", new { id = fieldPrefix + "isDeletedCheckBox", @class = "form-control input-sm", @style = "width: 50px;" })
                @Html.ValidationMessage(fieldPrefix + "isDeletedCheckBox", "", new { @class = "text-danger" })
            </div>
        </td>
        <td>       
            @Html.Editor(fieldPrefix + "PolicyRefCode", new { htmlAttributes = new { id = fieldPrefix + "PolicyRefCode", @class = "form-control input-sm", @style = "width: 150px;", @readonly = true } })
            @Html.ValidationMessage(fieldPrefix + "PolicyRefCode")
        </td>
        <td>
            @Html.Editor(fieldPrefix + "PolicyDocumentPath", new { id = fieldPrefix + "PolicyDocumentPath", htmlAttributes = new { @class = "form-control input-sm", type = "file", Name = "PolicyDocument[" + @prefx + "]" } })
            @Html.ValidationMessage(fieldPrefix + "PolicyDocument[i]", "", new { @class = "text-danger" })
        </td>
    </tr>
    ''


    Java script deleteRow() method is shown below.

    The user should not be able to delete all records. It must remain 1 record. The error message must be triggered if the user attempts to delete all the records. The error message shown below is not working perfectly.

    All checked boxes at any location in the table must be removed if deleRow() is clicked 

    When I deleted on the same page twice without refreshing it gives the Error Error "TypeError: Cannot read property 'checked' of null"

    Thank you in anticipation for your assistance.

     

     function deleteRow(tableID) {
            try {
                var table = document.getElementById(tableID);
                var rowCount = t able.rows.length;
                for (var i = 1; i < rowCount; i++) {
                    var c = document.getElementById("DocumentAttachment[X" + i + "].isDeletedCheckBox");
                    if (c.checked) {
                        if (rowCount <= 0) {
                            BootstrapDialog.alert("Cannot delete all the rows.");
                            break;
                        }
                        else {
                            c.closest("tr").remove();
                        }
                    }
                }
            } catch (e) {
                BootstrapDialog.alert(e);
            }
        }

    Wednesday, August 12, 2020 11:04 PM
  • User-1244692504 posted

    Thank you Bruce. The click even is working, the row is showing, the postback is working but the  HttpPostedFileBase PolicyDocument is returning null to the Controller.  Furthermore, the deleteRow() method in JavaScript is not working perfectly. 

    Once again thank you for your time.

    Thursday, August 13, 2020 8:31 AM
  • User-1330468790 posted

    Hi Lawrence_Ajayi,

     

    The HttpPostedFileBase PolicyDocument pass from the modal view is returning null to the Controller

    You should check the name of the text box which is defined as file type. It should be "PolicyDocument", not "PolicyDocument[" + i + "]".

     

    Java script deleteRow() method is shown below.

    The user should not be able to delete all records. It must remain 1 record. The error message must be triggered if the user attempts to delete all the records. The error message shown below is not working perfectly.

    You should check the  variable ‘rowCount’ value in the function deleteRow().The error message didn’t work is caused by the variable ‘rowCount’.It should be refreshed after each deletion.

    If the rowCount didn’t refresh,then you delete to only the table title left,it  will give the Error Error "TypeError: Cannot read property 'checked' of null".Because the  variable ’c’ won’t be acquired.

    You could refer to below codes to modify yours:

    function deleteRow(tableID) {
    
            try {
    
                var table = document.getElementById(tableID);
    
                var rowCount = table.rows.length;
    
                for (var i = 1; i < rowCount; i++) {
    
                    var row = table.rows[i];
    
                    var c = row.cells[2].childNodes[0];
    
                    if (c.checked)
    
                    {
    
                        if (rowCount <= 2) {
    
                            alert("Cannot delete all the rows.");
    
                            break;
    
                        }
    
                        else {
    
                            table.deleteRow(i);
    
                            rowCount--;
    
                        }
    
                    }
    
     
    
                }
    
            } catch (e) {
    
                BootstrapDialog.alert(e);
    
            }
    
        }

     

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 13, 2020 9:44 AM
  • User-1244692504 posted

    Thank you so much Sean. The HttpPostedFileBase is returning the List/Array. Please the problem now is that while processing the file upload it complains of the error below

    Index was out of range. Must be non-negative and less than the size of the collection.
    Parameter name: index

    my Controller is pasted below:

    Please how do I handle the For Loop to remove the error?

    public ActionResult EditClientPolicy(ClientPolicyViewModel model, HttpPostedFileBase[] DocumentAttachment)
            {
                if (ModelState.IsValid)
                {
                    string path = string.Empty;
                    string fileExt = string.Empty;
                    string fileName = string.Empty;
                    string extension = string.Empty; 
    
                      for (var i = 1; i <= model.Underwriting_PolicyFile.DocumentAttachment.Count; i++)
                            {
                                if (model.Underwriting_PolicyFile.DocumentAttachment[i] != null )
                                {
                                    fileName = Path.GetFileNameWithoutExtension(DocumentAttachment[i].FileName); // Get the filename
                                    extension = Path.GetExtension(DocumentAttachment[i].FileName);
                                    fileExt = Path.GetExtension(DocumentAttachment[i].FileName).Substring(1);
    
                                    fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;  //Create a unique signature file name to avoid duplication.
    
                                    model.Underwriting_PolicyFile.DocumentAttachment[i].PolicyDocumentPath = "~/PDFReport/Documents/" + fileName; // save the relative file path
                                    DocumentAttachment[i].SaveAs(Path.Combine(Server.MapPath("~/PDFReport/Documents/"), fileName)); //save the full path to HttpPostedFileBase File.
    
                                    //path = Path.Combine(Server.MapPath("~/PDFReport/Documents/"), Path.GetFileName(files[i].FileName));
    
                                    ViewBag.FileStatus = "File uploaded successfully. {path}";
                                }
                            }
    
                            updated = _underwritingService.AddAttachmentToPolicy(model, SelectedDebitNoteID, ref states);
                        }
                    }
              }
         }

    Again, thank you for your effort in the deleteRow() method. I have modified my script as shown below but still showing Error Error "TypeError: Cannot read property 'checked' of null"

    the modify script is pasted below:

      function deleteRow(tableID) {
            try {
                var table = document.getElementById(tableID);
                var rowCount = table.rows.length;
                for (var i = 1; i < rowCount; i++) {
                    var c = document.getElementById("Underwriting_PolicyFile.DocumentAttachment[X" + i + "].isDeletedCheckBox");
                    if (c.checked) {
                        if (rowCount <= 2) {
                            BootstrapDialog.alert("Cannot delete all the rows.");
                            break;
                        }
                        else {
                            c.closest("tr").remove(); // delete many checked rows together
    rowCount--; } } } } catch (e) { BootstrapDialog.alert(e); } }

    table.deleteRow(i); // delete only one row  was not used because it deletes only one rows.

    Lest I forget, Sihui Sun use iQuery posted below but it's submitting the whole form when AddRow, deleteRow or delete the last row is clicked, so I

    could not use it. I would have loved to use it if it's not because of the problem mentioned.

    <div class="row">
       @*The code here has not been modified, so it is omitted.*@
       <button id="JQuerytest-AddRow">JQuerytest-AddRow</button>
       <button id="JQuerytest-RemoveRow">JQuerytest-RemoveRow</button>
       <button id="JQuerytest-RemoveLastRow">JQuerytest-RemoveLastRow</button>
       @*The code here has not been modified, so it is omitted.*@
    </div>
    <link href="~/Content/bootstrap-dialog.css" rel="stylesheet" />
    @section scripts{
        <script src="~/Scripts/bootstrap-dialog.js"></script>
        <script>
            $("#JQuerytest-AddRow").click(function () {
                var clonedRow = $("#requestClientContacts tbody tr:first").clone();
                clonedRow.find('input').val('');
                clonedRow.find("input[type=checkbox]").attr("checked", false);
                $('#requestClientContacts tbody').append(clonedRow);
            });
            $("#JQuerytest-RemoveLastRow").click(function () {
                var count = $("#requestClientContacts tbody tr").length;
                if (count > 1) {
                    var clonedRow = $("#requestClientContacts tbody tr:last").remove();
                } else {
                    BootstrapDialog.alert("cannot delete all rows");
                }
            });
            $("#JQuerytest-RemoveRow").click(function () {
                var table = $("#requestClientContacts");
    
                //Annotated code implementation: the first line cannot be deleted
    
                //if (table.find("tbody tr:first").find("input[type=checkbox]").is(":checked")) {
                //    BootstrapDialog.alert("cannot delete all rows");
                //}
                //table.find("tbody tr:not(:first)").each(function () {
                //    if ($(this).find("input[type=checkbox]").is(":checked")) {
                //        $(this).remove();
                //    }
                //});
    
                //this cod:at least one must exist.
                var count = table.find("tbody tr").length;
                var selectcount =0;
                table.find("tbody tr").each(function () {
                    if ($(this).find("input[type=checkbox]").is(":checked")) {
                        selectcount++;
                    }
                });
                if (selectcount == count) {
                    BootstrapDialog.alert("cannot delete all rows");
                } else {
                    table.find("tbody tr").each(function () {
                        if ($(this).find("input[type=checkbox]").is(":checked")) {
                            $(this).remove();
                        }
                    });
                }
            });
          
      </script>
    }

    Thanks a million. 

    Best regards

    Thursday, August 13, 2020 10:48 PM
  • User-1244692504 posted

    Thank you all. I have found the answer to it

     for(var i =1; i <= model.Underwriting_PolicyFile.DocumentAttachment.Count; i++){

    }

    should have been coded as below
    for(var i = 0; i < model.Underwriting_PolicyFile.DocumentAttachment.Count; i++){

    }


    i have forgotten that the index begins from 0 and not 1
    and i must be less < than the total count for the error to go.
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, August 14, 2020 4:42 PM