---
title: "Attach multiple files gridview row in knockout js"  
description: "Attach multiple files gridview row in knockout js"  
author: "Anonymous User"  
published: 2016-02-22  
updated: 2016-02-22  
canonical: https://www.mindstick.com/forum/33990/attach-multiple-files-gridview-row-in-knockout-js  
category: "javascript"  
tags: ["jquery", "mvc", "knockout.js"]  
reading_time: 5 minutes  

---

# Attach multiple files gridview row in knockout js

we want to Attach [multiple files](https://answers.mindstick.com/qa/95163/how-do-i-convert-multiple-files-to-pdf) [gridview](https://www.mindstick.com/articles/873/update-delete-edit-gridview-in-asp-dot-net) [row](https://www.mindstick.com/forum/1212/this-row-already-belongs-to-this-table) in [knockout](https://www.mindstick.com/forum/33538/how-to-insert-data-in-database-using-knockout-js) js. how it is possible please help me.

## Replies

### Reply by Anonymous User

Hi '

we are providing code shown is below. I hope to help you.

**Index.cshtml**

```
@{    ViewBag.Title = "View2";    Layout = "~/Views/Shared/_Layout.cshtml";}<h2>View2</h2><style>    .ui-progressbar, .progressDiv {        position: relative;    }    .progress-label {        position: absolute;        left: 50%;        top: 4px;        font-weight: bold;        text-shadow: 1px 1px 0 #fff;    }    input[type="file"] {        opacity: 0;    }    #file {        background: url('images/folder_open-add.png') 0 0 no-repeat;        width: 100%;        height: 32px;        position: relative;        overflow: hidden;    }        #file label {            padding: 0 0 0 35px;            color: green;            width: 100%;        }        #file .fileInput {            line-height: 35px;            left: 0;            position: absolute;            width: 35px;        }</style><script src="~/Scripts/knockout-3.4.0.js"></script><script type="text/javascript">    function tableRow(guid, fileName, fileUrl, arrayFile) {        var self = this;        self.Guid = ko.observable(guid);        self.FileName = ko.observable(fileName);        self.FileUrl = ko.observable(fileUrl);        self.FileList = ko.observableArray([]);    }    function fileModel(fileName, extention, filepath, guid) {        var self = this;        self.Guid = ko.observable(guid);        self.FileName = ko.observable(fileName);        self.Extention = ko.observable(extention);        self.FilePath = ko.observable(filepath);    }    function tableRowsViewModel() {        var self = this;        self.tableRows = ko.observableArray();        self.arrayNew = ko.observableArray();        self.addNewRow = function () {            self.tableRows.push(new tableRow(Math.random().toString(36).substring(9), '', '', []));        }        self.save = function () {            $.post("/Home/Save", { obj: ko.toJSON(this.tableRows()) }, function (data) {                console.log(JSON.stringify(this.tableRows()));            });        },        self.select = function () {            $('#inputFile').attr("data", this.Guid());            var Gid = this.Guid()            var findItem = ko.utils.arrayFilter(vm.tableRows(), function (item) {                return (item.Guid() === Gid);            });            self.arrayNew.removeAll();            findItem[0].FileList().forEach(function (item) {                self.arrayNew.push(item);            });            var dialog            dialog = $("#dialog-form").dialog({                autoOpen: false,                height: 300,                width: 350,                modal: true,                buttons: {                    Ok: function () {                        dialog.dialog("close");                    }                }            });            dialog.dialog("open");            self.remove = function (item) {                if (!confirm("Do you want to delete")) {                    return false;                }                $.post("/Home/Remove", { obj: ko.toJSON(item) }, function (data) {                    self.tableRows.remove(item);                });            }        },        self.selected = function (data, event) {            $('#progressDiv').progressbar({                value: 10,                max: 100,                change: function (e) {                    $('.progress-label').text($('#progressDiv').progressbar("value") + "%");                }            });             var path = $("#inputFile").val();            var formData = new FormData();            var file = document.getElementById("inputFile").files[0];            formData.append("file", file);            var divElem = $('#progressDiv');            $.ajax({                type: "POST",                url: '/Home/UploadImage',                data: formData,                dataType: 'json',                contentType: false,                processData: false,                success: function (response) {                    var findItem = ko.utils.arrayFilter(vm.tableRows(), function (item) {                        return (item.Guid() === $("#inputFile").attr("data"));                    });                    console.log(response.Extention);                    findItem[0].FileList.push(new fileModel(response.FileName, response.Extention, response.FilePath, response.Guid));                    self.arrayNew.push(new fileModel(response.FileName, response.Extention, response.FilePath, response.Guid));                    $("#progressDiv").progressbar("destroy");                    $('.progress-label').text('');                    $("#inputFile").val('');                },                xhr: function () {                    var xhr = $.ajaxSettings.xhr();                    if (xhr.upload) {                        xhr.upload.addEventListener('progress', function (evt) {                            var percent = Math.floor((evt.loaded / evt.total) * 100);                            divElem.progressbar("value", percent);                        }, false);                    }                    return xhr;                },                error: function (error) {                    alert("errror");                }            });          };        self.RemoveImage = function (file) {            if (!confirm("Do you want to delete")) {                return false;            }            var Gid = $('#inputFile').attr("data");            var findItem = ko.utils.arrayFilter(vm.tableRows(), function (item) {                return (item.Guid() === Gid);            });                       $.ajax({                type: "POST",                data:{ guid: file.Guid(), extention: file.Extention() },                url: "@Url.Action("RemoveImage", "Home")",                success: function (data) {                    findItem[0].FileList.removeAll();                    self.arrayNew.remove(file);                    self.arrayNew().forEach(function (item) {                        findItem[0].FileList.push(item);                    });                },                error: function (error) {                    alert(error.status + "<--and--> " + error.statusText);                }            });          @*  $.post("@Url.Action("RemoveImage", "Home")", { guid: file.Guid(), extention: file.Extention() }, function (data) {                console.log(data);                findItem[0].FileList.removeAll();                self.arrayNew.remove(file);                self.arrayNew().forEach(function (item) {                    findItem[0].FileList.push(item);                });            })*@         };    }    var vm = new tableRowsViewModel();    $(document).ready(function () {        ko.applyBindings(vm);    });</script><div id="tabs">    <ul>        <li><a href="#tabs-1">File Upload</a></li>    </ul>    <div id="tabs-1">        <table>            <thead>                <tr>                    <th>Guid                    </th>                    <th>FileName                    </th>                    <th>FileUrl                    </th>                    <th>Attech                    </th>                    <th>Action                    </th>                </tr>            </thead>            <tbody data-bind="foreach: tableRows">                <tr>                    <td>                        <input type="text" style="width: 100px;" data-bind="value: Guid" />                    </td>                    <td>                        <input type="text" style="width: 100px;" data-bind="value: FileName" />                    </td>                    <td>                        <input type="text" style="width: 100px;" data-bind="value: FileUrl" />                    </td>                    <td>                        <button type="button" data-bind="click: $root.select">                            Select File                        </button>                    </td>                    <td>                        <button type="button" data-bind="click:$root.remove">                            Delete                        </button>                    </td>                </tr>                   <tr>                    <td colspan="4">                        <table>                            <tbody data-bind="foreach: FileList">                                <tr>                                    <td data-bind="text: FileName"></td>                                     <td data-bind="text: Extention"></td>                                </tr>                            </tbody>                        </table>                    </td>                </tr>            </tbody>            <tfoot>                <tr>                    <td colspan="4">                        <button type="button" data-bind="click: addNewRow">                            add row                        </button>                        <button type="button" data-bind="click: save">                            Save                        </button>                    </td>                </tr>            </tfoot>        </table>        <div>            <div id="dialog-form" title="Upload File" style="display: none;">                <input type="hidden" value="" id="hiddenid" />                <div id='file'>                    <label for="inputFile">                        <input type="file" id='inputFile' class='fileInput' data="" data-bind="event:{change:selected}" />                    </label>                </div>                @* <input type="file" name="file" id="file" data="" data-bind="event:{change:selected}" />*@                <br />                <table>                    <tbody data-bind="foreach: arrayNew">                        <tr>                            <td data-bind="text: FileName"></td>                            <td>                                <button type="button" data-bind="click:$root. RemoveImage">                                    X                                </button>                            </td>                        </tr>                    </tbody>                </table>                <div id="progressDiv">                    <div class="progress-label"></div>                </div>            </div>        </div>    </div></div> 
```

```
HomeControllerusing System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.Script.Serialization;using System.Web.UI.WebControls;namespace ForceLMS_DEMO.Controllers{    public class HomeController : Controller    {        public ActionResult Index()        {            return View();        }        [HttpPost]        public JsonResult Save(string obj = null)        {            JavaScriptSerializer Serializer = new JavaScriptSerializer();            var selected = Serializer.Deserialize<List<tableRow>>(obj).ToList();            foreach (tableRow re in selected)            {                foreach (FileList fe in re.FileList)                {                }            }             return Json("success", JsonRequestBehavior.AllowGet);        }        [HttpPost]        public JsonResult Remove(string obj = null)        {            JavaScriptSerializer Serializer = new JavaScriptSerializer();            var selected = Serializer.Deserialize<tableRow>(obj);                            foreach (FileList fe in selected.FileList)                {                    var fullPath = Path.Combine(Server.MapPath("~/Fileimg"),  fe.Guid + fe.Extention);                    if (System.IO.File.Exists(fullPath))                    {                        System.IO.File.Delete(fullPath);                        ViewBag.deleteSuccess = "success";                    }                                 }                return Json(new { message = ViewBag.deleteSuccess }, JsonRequestBehavior.AllowGet);        }        [HttpPost]        public JsonResult UploadImage(HttpPostedFileBase file)        {            try            {                if (file != null)                {                    var fileName = Path.GetFileName(file.FileName);                    var extention = Path.GetExtension(file.FileName);                    var guid = Guid.NewGuid();                    var path = Path.Combine(Server.MapPath("~/Fileimg"), guid + extention);                    file.SaveAs(path);                    return Json(new { Success = true, message = "success", FileName = fileName,Extention=extention, FilePath = path, Guid = guid }, JsonRequestBehavior.AllowGet);                }                else                {                    return Json(new { Success = false, message = "unsuccess" }, JsonRequestBehavior.AllowGet);                }            }            catch (Exception ex)            {                return Json(new { success = false, message = ex.Message }, JsonRequestBehavior.AllowGet);            }        }        [HttpPost]        public JsonResult RemoveImage(string guid ,string extention)        {            ViewBag.deleteSuccess = "unsuccess";            var photoName = "";            photoName = guid;            var fullPath = Path.Combine(Server.MapPath("~/Fileimg"), photoName + extention );            if (System.IO.File.Exists(fullPath))            {                System.IO.File.Delete(fullPath);                ViewBag.deleteSuccess = "success";            }            return Json(new { message = ViewBag.deleteSuccess }, JsonRequestBehavior.AllowGet);        }        public class tableRow        {            public string Guid { get; set; }            public string FileName { get; set; }            public string FileUrl { get; set; }            public List<FileList> FileList { get; set; }        }        public class FileList        {            public string Guid { get; set; }            public string FileName { get; set; }            public string FilePath { get; set; }            public string Extention { get; set; }                    }    }} 
```

```
Result  
```


---

Original Source: https://www.mindstick.com/forum/33990/attach-multiple-files-gridview-row-in-knockout-js

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
