首页 > 解决方案 > 如何重新加载显示已上传新数据的视图

问题描述

我有一个 ASP.Net Core MVC 3.1 应用程序。在我的网页上,我有一个上传控件,用户可以在其中上传照片。我有一个按钮,它遍历所选文件列表并将信息添加到数据库并将照片复制到特定位置。在我的控制器中完成此操作后,我再次调用我的视图。当我进入查看代码以获取我上传的照片但没有显示数据和照片时。我必须按 f5 来刷新页面。请有任何想法。我的代码如下:

控制器: -

        private readonly AppDBContext context;
        private readonly UserManager<ApplicationUser> userManager;
        private readonly IWebHostEnvironment hostEnvironment;

        public PhotosController(UserManager<ApplicationUser> userManager, AppDBContext context,
            IWebHostEnvironment hostingEnvironment)
        {
            this.context = context;
            this.userManager = userManager;
            this.hostEnvironment = hostingEnvironment;
        }
        public IActionResult Index()
        {
            return View();
        }

        private PhotosViewModel PopulateLists(int customer_Id, Int16 photoStage)
        {
            PhotosViewModel photoLists = new PhotosViewModel();
            if (photoStage == 0)
            {
                photoLists.PhotosList = context.JobPhotos.Where(s => s.CustomerId == customer_Id).ToList();
            } else
            {
                photoLists.PhotosList = context.JobPhotos.Where(s => s.CustomerId == customer_Id &&  s.PhotoStage == photoStage).ToList();
            }
            photoLists.photoStages = context.Lookups.Where(s => s.Lookup_Type_Id==21).ToList();
            photoLists.photoStages.Insert(0, new Lookups { Id = 0, Description = "Select" });
            return photoLists;
        }
        public IActionResult GetPhotos(Int16 photoStage)
        {
            return View("Photos", PopulateLists(GetCustomerId(),photoStage));
        }

        public Int32 GetCustomerId()
        {
            string cust_Id = JsonConvert.DeserializeObject(HttpContext.Session.GetString("customer_Id")).ToString();
            return Int32.Parse(cust_Id);
        }
        public IActionResult deletePhotoYesNo()
        {
            string photoPath = JsonConvert.DeserializeObject(HttpContext.Session.GetString("photoPath")).ToString();
            JobPhotos jobPhoto = context.JobPhotos.Where(p => p.PhotoPath == photoPath).FirstOrDefault();
            if (jobPhoto != null)
            {
                return View("DeletePhoto", jobPhoto);
            }
            return View("Photos", PopulateLists(GetCustomerId(),0));
        }
        public IActionResult deletePhoto(string photoPath)
        {
            JobPhotos jobPhoto = context.JobPhotos.Where(p => p.PhotoPath == photoPath).FirstOrDefault();
            if (jobPhoto != null)
            {             
                context.JobPhotos.Remove(jobPhoto);
                context.SaveChanges();
            }
            return View("Photos", PopulateLists(GetCustomerId(),0));
        }
        public Int16 GetPhotoStage()
        {
            if (HttpContext.Session.GetString("photoStage") == null) return 0;
            string photoStage = JsonConvert.DeserializeObject(HttpContext.Session.GetString("photoStage")).ToString();
            return Int16.Parse(photoStage);
        }
        public void SetPhotoStage(string photoStage)
        {
            HttpContext.Session.SetString("photoStage", JsonConvert.SerializeObject(photoStage));
        }
        public void ClearPhotoStage()
        {
            HttpContext.Session.SetString("photoStage", JsonConvert.SerializeObject(""));
        }
        public IActionResult Create(IList<IFormFile> files)
        {
            //Make sure a photo stage is selected.
            if (GetPhotoStage() == 0)
            {
                return RedirectToAction("GetPhotos", "Photos", new { customer_Id = GetCustomerId() });
            }
            List<ApplicationUser> users = userManager.Users.ToList();
            string FullName = users.Find(x => x.Email == User.FindFirstValue(ClaimTypes.Email)).FullName;
            Int16 photoStage = 0;

            if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                    //If customer Id sub folder in the photos folder does not exist create it.
                    string photoFolder = Path.Combine(Path.Combine(hostEnvironment.WebRootPath, "Photos"), GetCustomerId().ToString());
                    photoStage = GetPhotoStage();
                    photoFolder = Path.Combine(photoFolder, photoStage.ToString());
                    if (!Directory.Exists(photoFolder))
                    {
                        Directory.CreateDirectory(photoFolder);
                    }
                    foreach (IFormFile photo in files)
                    {
                        uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName;
                        string filePath = Path.Combine(photoFolder, uniqueFileName);
                        photo.CopyTo(new FileStream(filePath, FileMode.Create));
                        
                        JobPhotos jobPhoto = new JobPhotos
                        {
                            CustomerId = GetCustomerId(),
                            CreatedBy = FullName,
                            DateCreated = DateTime.Now,
                            PhotoStage = photoStage,
                            PhotoPath = GetCustomerId() + "/" + photoStage + "/" + uniqueFileName,
                        };
                        context.JobPhotos.Add(jobPhoto);
                        context.SaveChanges();
                    }
            }
            ModelState.Clear();
            return View("Photos", PopulateLists(GetCustomerId(), photoStage));

            //return RedirectToAction("GetPhotos", "Photos", new { photoStage = GetPhotoStage() });
        }
        public JsonResult GetValue(string path)
        {
            List<JobPhotos> jobPhotos = context.JobPhotos.Where(s => s.PhotoPath == path).ToList();

            if (jobPhotos.Count() > 0)
            {
                var data = new JobPhotos
                { 
                    Id = jobPhotos[0].Id,
                    CustomerId = jobPhotos[0].CustomerId,
                    PhotoPath = jobPhotos[0].PhotoPath.ToString(),
                    CreatedBy = jobPhotos[0].CreatedBy,
                    DateCreated = jobPhotos[0].DateCreated,
                    PhotoStage = jobPhotos[0].PhotoStage
                };
                HttpContext.Session.SetString("photoPath", JsonConvert.SerializeObject(data.PhotoPath));
                return Json(data);
            } else
            {
                var data = new JobPhotos
                {
                    CreatedBy = "",
                    DateCreated = null,
                    PhotoStage = 0
                };
                return Json(data);
            }
        }
        public IActionResult Back()
        {
            return RedirectToAction("EditCustomer","CustomerDetails", new { customer_Id = GetCustomerId()});
        }

看法: -

@model PhotosViewModel

<link href="~/CSS/Photos.css" rel="stylesheet" />

<form enctype="multipart/form-data" asp-controller="Photos" asp-action="create" method="post" class="mt-3">
    <div class="container">
        <div class="row align-items-start">
            <div class="col-12">
                <a id="Post" class="btn btn-primary float-right mt-2" asp-controller="Photos" asp-action="GetPhotos" asp-route-photoStage="107" style="width: 120px; margin-right: 268px;"><span class="fas fa-file-upload"></span><span> Post-Job</span></a>
                <a id="Mid" class="btn btn-primary float-right mt-2" asp-controller="Photos" asp-action="GetPhotos" asp-route-photoStage="106" style="width: 120px; margin-right: 87px;"><span class="fas fa-file-upload"></span><span> Mid-Job</span></a>
                <a id="Pre" class="btn btn-primary float-right mt-2" asp-controller="Photos" asp-action="GetPhotos" asp-route-photoStage="105" style="width: 120px; margin-right: 95px;"><span class="fas fa-file-upload"></span><span> Pre-Job</span></a>
            </div>
        </div>
        <div id="divCarousel" class="carousel slide" data-interval="false" data-ride="carousel">
            @*<ul class="carousel-indicators">
                @{
                    int Pos = 0;
                }
                @foreach (var photo in Model.PhotosList)
                {
                    if (Pos == 0)
                    {
                        <li data-target="=#divCarousel" data-slide-to=@photo.Id class="active"></li>
                    }
                    else
                    {
                        <li data-target="=#divCarousel" data-slide-to=@photo.Id></li>
                    }
                    Pos++;
                }
            </ul>*@
            <!-- The slideshow -->
            <div class="carousel-inner">
                @{
                    Int16 i = 0;
                }
                @foreach (var photo in Model.PhotosList)
                {

                    var photoPath = "~/Photos/" + photo.PhotoPath;

                    if (i == 0)
                    {
                        <div class="carousel-item active">
                            <img class="photoSize" src="@photoPath" alt="No Photo" asp-append-version="true">
                        </div>
                    }
                    else
                    {
                        <div class="carousel-item">
                            <img class="photoSize" src="@photoPath" alt="No Photo" asp-append-version="true">
                        </div>
                    }
                    i++;
                }
            </div>
            <!-- Left and right controls -->
            <a class="carousel-control-prev" href="#divCarousel" data-slide="prev">
                <span class="carousel-control-prev-icon"></span>
            </a>
            <a class="carousel-control-next" href="#divCarousel" data-slide="next">
                <span class="carousel-control-next-icon"></span>
            </a>
        </div>
        <div class="row align-items-start mt-3">
            <div class="col-2">
                <label class="col-sm-2 col-form-label"></label>
            </div>
            <div class="col-8">
                <div class="custom-file">
                    <input id="inpFiles" name="inpFiles" asp-for="Photos" class="form-control custom-file-input" accept="image/*" />
                    <label class="custom-file-label">Choose Photo...</label>
                </div>
            </div>
            <div class="col-2 mt-1">
                <button id="butSave" type="button" class="btn btn-primary" data-toggle="tooltip" data-placement="right" title="Save"><span class="fas fa-file-upload"></span></button>
            </div>
        </div>
        <div class="row align-items-start mt-1">
            <div class="col-2">
                <label class="col-sm-2 col-md-12 col-form-label">Created Date</label>
            </div>
            <div class="col-4">
                <input id="txtDateCreated" class="form-control" placeholder="Created Date" readonly="readonly" />
            </div>
        </div>
        <div class="row align-items-start mt-1">
            <div class="col-2">
                <label class="col-sm-2 col-md-12 col-form-label">Created By</label>
            </div>
            <div class="col-4">
                <input id="txtCreatedBy" class="form-control" placeholder="Created By" readonly="readonly" />
            </div>
        </div>
        <div class="row align-items-start mt-1">
            <div class="col-2">
                <label class="col-sm-2 col-md-12 col-form-label">Photo Stage</label>
            </div>
            <div class="col-4">
                <select id="drpPhotoStages" asp-items="@(new SelectList(Model.photoStages, "Id", "Description",0))" class="selectpicker"></select>
            </div>
        </div>
        <a class="btn btn-danger float-right mt-2" asp-controller="Photos" asp-action="deletePhotoYesNo" style="width: 100px; margin-right: 20px;" )><span class="fas fa-trash-alt"></span><span> Delete</span></a>
        <a class="btn btn-primary float-right mt-2" asp-controller="Photos" asp-action="back" style="width: 100px; margin-right: 20px;" )><span class="fas fa-hand-point-left"></span><span> Back</span></a>
    </div>
    <div class="modal" id="messageModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Save Photos Error</h4>
                    <button class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    <p>You need to select a photo stage in order to upload the selected photos...</p>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-primary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    @section Scripts {
        <script>
            function showPhotoDetails() {
                //validate that there are photos to start with.
                if ($('.carousel-item.active img').attr('src') == undefined) return;

                var url = $('.carousel-item.active img').attr('src');
                var photopath = url.split('?');
                photopath[0] = photopath[0].substring(8, photopath[0].length);

                $.ajax({
                    type: 'POST',
                    url: "/Photos/GetValue?path=" + photopath[0],
                    dataType: "json",
                    async: false,
                    success: function (data) {
                        $("input#txtCreatedBy").val(data.createdBy);
                        $("input#txtDateCreated").val(data.dateCreated);
                        $("input#txtCreatedBy").val(data.createdBy);
                        $("#drpPhotoStages").val(data.photoStage);
                        $.ajax({
                            type: 'POST',
                            url: "/Photos/SetPhotoStage?photoStage=" + data.photoStage,
                            dataType: "json",
                            async: false,
                            success: function () {
                            }
                        });
                    }
                });
            }
            function uploadPhotos() {
                var input = document.getElementById("inpFiles");
                var files = input.files;
                var formData = new FormData();
                for (var i = 0; i != files.length; i++) {
                    formData.append("files", files[i]);
                }
                $.ajax({
                    type: "POST",
                    url: "/Photos/Create",
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function () {

                    }
                });
            }

            $(document).ready(function () {
                showPhotoDetails();
                $('.custom-file-input').on("change", function () {
                    var fileLabel = $(this).next('.custom-file-label');
                    var files = $(this)[0].files;
                    if (files.length > 1) {
                        fileLabel.html(files.length + ' files selected.');
                    } else if (files.length == 1) {
                        fileLabel.html(files[0].name);
                    }
                });
                $("#divCarousel").on('slid.bs.carousel', function () {
                    showPhotoDetails();
                });
                $("#drpPhotoStages").on('change', function () {
                    $.ajax({
                        type: 'POST',
                        url: "/Photos/SetPhotoStage?photoStage=" + this.value,
                        dataType: "json",
                        async: false,
                        success: function () {
                        }
                    });
                });
                $("#butSave").on('click', function () {
                    if ($("#drpPhotoStages option:selected").val() == 0) {
                        $("#messageModal").modal('show');
                    } else {
                        uploadPhotos();
                    }
                    //if ($('select[name=drpPhotoStages] option').filter(':selected'), val() == 0) {
                    //    alert('Please select a photo stage...');
                    //}
                })
            });
        </script>
    }
</form>

在我的创建操作中,我保存照片,然后再次调用我的视图,其中包含我上传的照片,但没有显示任何内容。正如我所说,我必须按 F5。

标签: .net-corepageload

解决方案


推荐阅读