Display File Name on Edit Button Click using AngularJS in ASP.Net MVC

Last Reply one month ago By dharmendr

Posted one month ago

HI,

Based upon below url i am going to do edit functionality.

currently my requirement is that after clicking of edit button need to display relevant file name aside of textbox.

Could you please help me

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

You are viewing reply posted by: dharmendr one month ago.
Posted one month ago

Hi mahesh213,

Refe 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(System.IO.Path.Combine(Server.MapPath("~/Files/"), 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 = System.IO.Path.Combine(Server.MapPath("~/Files/"), 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("~/Files/"), fileName));
        }
        Form st = JsonConvert.DeserializeObject<Form>(Request.Form["details"]);
        if (!string.IsNullOrEmpty(st.Name))
        {
            Form state = new Form();
            state.Name = st.Name;
            state.Resume = System.IO.Path.Combine(Server.MapPath("~/Files/"), 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 id)
    {
        try
        {
            int no = Convert.ToInt32(id);
            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 xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Index</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.8/angular.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" src="https://cdnjs.cloudflare.com/ajax/libs/danialfarid-angular-file-upload/12.2.13/ng-file-upload.min.js"></script>
    <script type="text/javascript">
        var app = angular.module("MyApp", ['ngFileUpload', 'angularUtils.directives.dirPagination']);
        app.controller("MyController", ['$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 = true;
                var getData = myService.getState(state.Id);
                getData.then(function (emp) {
                    $scope.Id = emp.data[0].Id;
                    $scope.Name = emp.data[0].Name;
                    $scope.Resume = emp.data[0].Resume.split('\\')[emp.data[0].Resume.split('\\').length - 1];
                    $scope.Action = "Edit";
                },
                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-app="MyApp" ng-controller="MyController">
    <div class="container">
        <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 />
                            <span>{{Resume}}</span>
                        </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>Id</th>
                            <th>File</th>
                            <th>Name</th>
                            <th>Actions</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" class="btn btn-default btn-sm" ng-click="editState(state)" >Edit</button></td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Screenshot