Home > DeveloperSection > Forums > Attach multiple files gridview row in knockout js
Ankit Singh

Total Post:341

Points:2389
Posted on    February-22-2016 5:53 AM

 JavaScript JQuery  Mvc  Knockout.js 
Ratings:


 1 Reply(s)
 324  View(s)
Rate this:
we want to Attach multiple files gridview row in knockout js. how it is possible please help me. 


aditya kumar Patel

Total Post:247

Points:1759
Posted on    February-22-2016 6:02 AM

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>

 

HomeController

using 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

 

 

 


Don't want to miss updates? Please click the below button!

Follow MindStick