Upload and display File name in HTML Table using AngularJS in ASP.Net MVC

Last Reply one year ago By dharmendr

Posted one year ago

HI,

i have one table named as State with fields

Id ,Name and Resume

1)After adding new records i have to save to grid view but here resume value is not displaying

I need to dipsplay only file name(Resume) in grid view

2) After clicking of edit button in grid view i need to display relevant values on form here resume values also displaying null

i need to display file name at upload a file

Please look at my screenshot how i am geeting result

and what i need

https://ibb.co/r6m5wZK

I need to display value on File in grid view

in the same way after clicking of edit button i need to display relevant file name on form and save to database

Posted one year ago Modified on one year ago

Hi mahesh213,

In edit click you can't assign value to fileupload control. You need to select file again for upload. If you do not select any file then previous file retain for that record.

Refer below code.

Controller

public class HomeController : Controller
{
    MasterEntities db = new MasterEntities();
    // GET: /Home/
    public ActionResult Index()
    {
        return View();
    }

    public JsonResult UpdateState2()
    {
        string fileName = "";
        for (int i = 0; i < Request.Files.Count; i++)
        {
            HttpPostedFileBase postedFile = Request.Files[i];
            if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
            {
                string[] file = postedFile.FileName.Split(new char[] { '\\' });
                fileName = file[file.Length - 1];
            }
            else
            {
                fileName = postedFile.FileName;
            }
            postedFile.SaveAs(Path.Combine(Server.MapPath("~/App_Data/"), fileName));
        }
        Form st = JsonConvert.DeserializeObject<Form>(Request.Form["details"]);
        if (!string.IsNullOrEmpty(st.Name))
        {
            int no = Convert.ToInt32(st.Id);
            var stateList = db.Forms.Where(x => x.Id == no).FirstOrDefault();

            stateList.Name = st.Name;
            if (!string.IsNullOrEmpty(fileName))
            {
                stateList.Resume = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
            }
            db.SaveChanges();
            return Json(db.Forms, JsonRequestBehavior.AllowGet);
        }
        else
        {
            return Json("Addition of state unsucessfull !", JsonRequestBehavior.AllowGet);
        }
    }

    public JsonResult AddState()
    {
        string fileName = "";
        for (int i = 0; i < Request.Files.Count; i++)
        {
            HttpPostedFileBase postedFile = Request.Files[i];
            if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
            {
                string[] file = postedFile.FileName.Split(new char[] { '\\' });
                fileName = file[file.Length - 1];
            }
            else
            {
                fileName = postedFile.FileName;
            }
            postedFile.SaveAs(Path.Combine(Server.MapPath("~/App_Data/"), fileName));
        }
        Form st = JsonConvert.DeserializeObject<Form>(Request.Form["details"]);
        if (!string.IsNullOrEmpty(st.Name))
        {
            Form state = new Form();
            state.Name = st.Name;
            state.Resume = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
            //state.Resume = fileName;
            db.Forms.AddObject(state);
            db.SaveChanges();
            return Json(db.Forms, JsonRequestBehavior.AllowGet);
        }
        else
        {
            return Json("Addition of state unsucessfull !", JsonRequestBehavior.AllowGet);
        }
    }

    public JsonResult getEmployeeByNo(string EmpNo)
    {
        try
        {
            int no = Convert.ToInt32(EmpNo);
            var employeeList = db.Forms.Where(x => x.Id == no);
            return Json(employeeList, JsonRequestBehavior.AllowGet);
        }
        catch (Exception exp)
        {
            return Json("Error in getting record !", JsonRequestBehavior.AllowGet);
        }
    }

    public JsonResult getAll1()
    {
        try
        {
            var employeeList = db.Forms;
            return Json(employeeList, JsonRequestBehavior.AllowGet);
        }
        catch (Exception exp)
        {
            return Json("Error in getting record !", JsonRequestBehavior.AllowGet);
        }
    }
}

View

<html ng-app="myApp">
<head runat="server">
    <title>Index</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.full.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.8/angular.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/danialfarid-angular-file-upload/12.2.13/ng-file-upload.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/angular-utils-pagination@0.11.1/dirPagination.js"></script>
    <script type="text/javascript">
        var app = angular.module("myApp", ['ngFileUpload', 'angularUtils.directives.dirPagination']);
        app.controller("myCntrl", ['$scope', '$http', 'myService', function ($scope, $http, myService) {
            $scope.mahesh = false;
            GetAllTerms();
            function GetAllTerms() {
                var getData = myService.getterms();
                getData.then(function (tc) {
                    $scope.terms = tc.data;
                }, function (tc) {
                    alert("Records gathering failed!");
                });
            }
            $scope.UploadFiles = function (files) {
                $scope.SelectedFiles = files;
            };
            //edit by id
            $scope.editState = function (state) {
                GetAllTerms();
                $scope.mahesh = $scope.mahesh ? false : true;
                var getData = myService.getState(state.Id);
                getData.then(function (emp) {
                    $scope.employee = emp.data;
                    $scope.Id = state.Id;
                    $scope.Name = state.Name;
                    $scope.SelectedFiles = state.Resume;
                    $scope.Action = "Edit";
                    $("#myModal").modal('show');
                },
                function (msg) {
                    //$("#alertModal").modal('show');
                    alert(msg.data);
                    $scope.msg = msg.data;
                });
                //$scope.$apply();

            }
            $scope.AddUpdateEmployee = function () {
                $scope.mahesh = $scope.mahesh;
                var getAction = $scope.Action;
                if (getAction == "Edit") {
                    var formData = new FormData();
                    var files = $scope.SelectedFiles;
                    if (files != undefined) {
                        for (var i = 0; i < files.length; i++) {
                            formData.append(files[i].name, files[i]);
                        }
                    }
                    var details = {};
                    details.Name = $scope.Name;
                    details.Id = $scope.Id;
                    formData.append("details", JSON.stringify(details));
                    var getData = myService.updateSta(formData);
                    getData.then(function (tc) {
                        $scope.terms = tc;
                    }, function (msg) {
                        alert(msg.data);
                        $scope.msg = msg.data;
                    });
                }
                else {
                    var formData = new FormData();
                    var files = $scope.SelectedFiles;
                    if (files != undefined) {
                        for (var i = 0; i < files.length; i++) {
                            formData.append(files[i].name, files[i]);
                        }
                    }
                    var details = {};
                    details.Name = $scope.Name;
                    formData.append("details", JSON.stringify(details));
                    var getData = myService.AddSt(formData);
                    getData.then(function (tc) {
                        $scope.terms = tc;
                    });
                }
            }
            $scope.AddStateDiv = function () {
                $scope.mahesh = $scope.mahesh ? false : true;
                $scope.Action = "Add";
            }
        } ]);

        app.service("myService", function ($http) {
            //get All countries
            this.getterms = function () {
                return $http.get("/Home/getAll1");
            };
            // get Employee By Id
            this.getState = function (employeeID) {
                var response = $http({
                    method: "post",
                    url: "/Home/getEmployeeByNo",
                    params: {
                        id: JSON.stringify(employeeID)
                    }
                });
                return response;
            }
            this.AddSt = function (employee) {
                var response = $.ajax({
                    url: '/Home/AddState',
                    type: "POST",
                    contentType: false,
                    processData: false,
                    data: employee
                });
                return response;
            }

            this.updateSta = function (employee) {
                var response = $.ajax({
                    url: "/Home/UpdateState2",
                    type: "POST",
                    contentType: false,
                    processData: false,
                    data: employee
                });
                return response;
            }
        });
    </script>
</head>
<body ng-controller="myCntrl">
    <div class="container">
        <div>
            <div id="wrapper" class="clearfix" ng-show="mahesh">
                <form name="userForm" novalidate>
                <h4 class="modal-title" style="text-align: center;">
                    {{Action}} State Details
                </h4>
                <div class="form-horizontal">
                    <div class="form-row">
                        <div class="col-md-4">
                            <label for="COI_Name">
                                Upload a file
                            </label>
                            <input type="file" ngf-select="UploadFiles($files)" />
                        </div>
                        <div>
                            <div class="col-md-4">
                                <label for="Name">
                                    Name
                                </label>
                                <input type="text" class="form-control" name="Name" ng-model="Name" placeholder="Enter  State Name"
                                    required />
                            </div>
                        </div>
                    </div>
                    <div>
                    </div>
                    <div class="form-group">
                    </div>
                    <div class="form-group" style="width: 120%; text-align: center; padding: 10px;">
                        <div class="col-md-offset-2 col-md-5">
                            <p>
                                <button class="btn btn-success btn-sm" ng-model="IsVisible" ng-click="AddUpdateEmployee()">
                                    <span class="glyphicon glyphicon-ok"></span>Submitt
                                </button>
                                <button class="btn btn-danger btn-sm" ng-click="close()">
                                    <span class="glyphicon glyphicon-remove"></span>Close
                                </button>
                            </p>
                        </div>
                    </div>
                </div>
                </form>
            </div>
            <button class="btn btn-success btn-sm " ng-click="AddStateDiv();" style="margin-left: 15px;">
                Add Country
            </button>
            <hr style="width: 550px;" />
            <div id="dvContainer">
                <div>
                    <div class="table-responsive " style="overflow-x: auto;">
                        <table id="dvData" cellpadding="12" class="table table-bordered table-hover table-striped"
                            style="margin-left: 20px; margin-right: 20px;">
                            <tr class="success">
                                <th><b>Id</b></th>
                                <th><b>File</b></th>
                                <th><b>Name</b></th>
                                <th><b>Actions</b></th>
                            </tr>
                            <tr dir-paginate="state in terms |orderBy:sortKey:reverse|itemsPerPage:10" ng-model="search">
                                <td>{{state.Id}}</td>
                                <td>{{state.Resume.split('\\')[state.Resume.split('\\').length-1]}}</td>
                                <td>{{state.Name }}</td>
                                <td><button type="button" ng-click="editState(state)" readonly>Edit</button></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Screenshot