locked
My index html page is not giving updated view after calling redirect to action RRS feed

  • Question

  • User-1355965324 posted

    If  you feel I posted duplicate I apologise for that. I am trying to get  updated record in index view page. I have give my code in details. If any one can help me it would be very appreciate

    model class
    public class EmpDocsViewModel
        {
    
            public int EmpDocID { get; set; }
            public int DepotNo { get; set; }
            public int DepartmentID { get; set; }
            public int EmployeeID { get; set; }
            public int DocCatID { get; set; }
            public string Comment { get; set; }
            [NotMapped]
            public string EmpName { get; set; }
            [NotMapped]
            public string UploadedDate { get; set; }
            public IEnumerable<EmpDocumentModel> EmpDocumentList { get; set; }
        }
    index controller
    
    public IActionResult EmpDocReIndex()
    {
    if (Convert.ToInt32(TempData["SelectedDepot"]) > 0)
                {
                    empDocModel.DepotNo = Convert.ToInt32(TempData["SelectedDepot"]);
                }
    
                if (Convert.ToInt32(TempData["SelectedDept"]) > 0)
                {
                    empDocModel.DepartmentID = Convert.ToInt32(TempData["SelectedDept"]);
                }
    
                if (Convert.ToInt32(TempData["SelectedEmpID"]) > 0)
                {
                    empDocModel.EmployeeID = Convert.ToInt32(TempData["SelectedEmpID"]);
                }
                
                empDocModel.DocCatID = 0;
                ViewBag.Employee = _unitOfWork.Employee.GetEmployeesByDepotAndDepartmentForDropdown(HttpContext.Session.GetInt32("UserID") ?? 0, empDocModel.DepotNo, empDocModel.DepartmentID);
                ViewBag.Category = _unitOfWork.DocumentRepository.GetAllEmpDocCatForDropdown();
    
                var empdoc = _unitOfWork.DocumentRepository.GetEmpDocuments(empDocModel.DepotNo, empDocModel.DepartmentID, empDocModel.DocCatID, empDocModel.EmployeeID);
                empDocModel.EmpDocumentList = empdoc;
                return View(empDocModel);  // The record not get updated after delete. In Sql it is updated
    }
    
      public IActionResult DeleteEmpDoc(int docid)
            {
                var docmodel = _unitOfWork.DocumentRepository.GetEmpDocumentsByID(docid);
                ViewBag.Depot = _unitOfWork.Depot.GetAllDepotsForDropdown(HttpContext.Session.GetInt32("UserID") ?? 0).ToList();
                ViewBag.Department = _unitOfWork.Department.GetAllDepartmentsForDropdown(HttpContext.Session.GetInt32("UserID") ?? 0).ToList();
                ViewBag.Employee = _unitOfWork.Employee.GetEmployeesByDepotAndDepartmentForDropdown(HttpContext.Session.GetInt32("UserID") ?? 0, docmodel.DepotNo, docmodel.DepartmentID);
                ViewBag.Category = _unitOfWork.DocumentRepository.GetAllEmpDocCatForDropdown();
                return PartialView("DeleteEmpDoc",docmodel);
            }
    
         
        [HttpPost]
            public IActionResult DeleteEmpDoc1(int docid)
            {
                 
                var docmodel = _unitOfWork.DocumentRepository.GetEmpDocumentsByID(docid);
                docmodel.IsDeleted = true;
                docmodel.DeletedBy = HttpContext.Session.GetInt32("UserID") ?? 0;
                docmodel.DeletedDateAndTime = DateTime.Now;
                long lideleted = _unitOfWork.DocumentRepository.Delete(docid, docmodel);
                TempData["SelectedDepot"] = docmodel.DepotNo;
                TempData["SelectedDept"] = docmodel.DepartmentID;
                TempData["SelectedEmpID"] = 500;
                TempData["SelectedCatID"] = 100;
                // The above value is apssing to the action
                return RedirectToAction("EmpDocReIndex", "EmpDoc");
                
            }
    
    Reindex chtml
    
    html
    <tbody>
                                        @foreach (var item in Model.EmpDocumentList)
                                        {
                                            <tr id="tr_@item.EmpDocID">
                                                <td>
                                                    @Html.DisplayFor(modelItem => item.EmpName)
                                                </td>
                                                <td>
                                                    @Html.DisplayFor(modelItem => item.UploadedDate)
                                                </td>
                                                <td>
    
                                                    @Html.DisplayFor(modelItem => item.NewFileName)
    
                                                </td>
    
    
                                                <td>
                                                    @Html.DisplayFor(modelItem => item.Comment)
                                                </td>
                                             
    
                                                <td id="tdDelete_@item.EmpDocID">
                                                    <a style="background-color: darkorange;" class="btn btn-primary form-control" data-toggle="tooltip"
                                                       onclick="ShowDeleteModalPopup(@item.EmpDocID)" title="Click here to delete record"><i class="fa fa-trash-alt"></i><span class="padding-left-ten">Delete</span></a>
                                                </td>
    
                                            </tr>
    
                                        }
    
    <div id="ShowEmpDocDeleteModal" class="modal fade" role="dialog">
            <div class="modal-dialog modal-lg">
                <!-- Modal content-->
                <div class="modal-content text-info">
                    
                    <div style="background-color:darkblue" class="modal-body" id="ShowEmpDocDiv">
    
                    </div>
                    
                   
                </div>
    
            </div>
        </div>
    
    function ShowDeleteModalPopup(id) {
            var url = '/EmpDoc/DeleteEmpDoc?docid=' + id;
            $("#ShowEmpDocDiv").load(url, function () {
                $("#ShowEmpDocDeleteModal").modal("show");
            })
        }
    
    
    DeleteEMp.html Partial View
    
     <div class="col-sm-2">
                                        <div class="center-block ">
                                            <button type="button" id="btnDelete" class="btn btn-primary form-control"> <i class="fa fa-save"></i><span class="padding-left-ten">Delete</span></button>
    
                                            
                                        </div>
                                    </div>
    
    
    function DeleteDocument() {
            $.ajax({
                type: "POST",
                url: "/EmpDoc/DeleteEmpDoc1?docid=" + $("#EmpDocID").val(),
                dataType: "json",
                success: function (data) {
                    alert("success")
                },
                failure: function (response) {
                    alert("failure")
                    console.log(response.responseText);
                },
                error: function (response) {
                    alert("error")
                    console.log(response.responseText);
                }
    
            });
    
    
        }
    
    public long Delete(long id, EmpDocumentModel docmodel)
    {
                long empdocid = 0;
                var empdoc = ctx.goEmpDocument.Find(Convert.ToInt32(id));
                if (empdoc != null)
                {
                    empdoc.IsDeleted = docmodel.IsDeleted;
                    empdoc.DeletedBy = docmodel.DeletedBy;
                    empdoc.DeletedDateAndTime = docmodel.DeletedDateAndTime;
                    empdocid = ctx.SaveChanges();
                }
                return empdocid;
    }
    
    public IEnumerable<EmpDocumentModel> GetEmpDocuments(int depotno, int departmentid, int docCatid, int employeeid)
            {
                IEnumerable<EmpDocumentModel> empdocs = (from doc in ctx.goEmpDocument
                                                         join cat in ctx.goDocCategory on doc.DocCatID equals cat.DocCatID
                                                         join emp in ctx.goEmployee on doc.EmployeeID equals emp.EmployeeID
                                                         where doc.IsDeleted == false
                                                         && doc.DepotNo == depotno
                                                         && doc.DepartmentID == departmentid
                                                         && doc.DocCatID == docCatid
                                                         && doc.EmployeeID == employeeid
                                                         select new EmpDocumentModel
                                                         {
                                                             EmpDocID = doc.EmpDocID,
                                                             UploadedDate = doc.CreatedDateAndTime == null ? "" : Convert.ToDateTime(doc.CreatedDateAndTime).ToShortDateString(),
                                                             NewFileName = doc.NewFileName,
                                                             EmpName = emp.EmployeeName,
                                                             Comment = doc.Comment
                                                         });
                return empdocs;
            }

    Thursday, February 13, 2020 10:29 PM

Answers

  • User665608656 posted

    Hi polachan,

    By testing your code, I found some issues in it.

    First of all, in your Partial View cshtml code, you did not add an onclick event to the button, so the DeleteDocument event will never be triggered.

    Secondly, when you use Ajax to call the DeleteEmpDoc1 action method, you need to return the content to the success method of ajax instead of directly RedirectToAction to refresh the page.

    I recommend that you redirect to the EmpDocReIndex action in js in the ajax success method.

    In addition, you need to pass the docid value of the data deleted by the current click to the partial view, and then pass the onclick event as a parameter to the DeleteEmpDoc1 method.

    For details, please refer to the following code:

      [HttpPost]
            public JsonResult DeleteEmpDoc1(int docid)
            {
                string message = "";
    try
    { var docmodel = _unitOfWork.DocumentRepository.GetEmpDocumentsByID(docid); docmodel.IsDeleted = true; docmodel.DeletedBy = HttpContext.Session.GetInt32("UserID") ?? 0; docmodel.DeletedDateAndTime = DateTime.Now; long lideleted = _unitOfWork.DocumentRepository.Delete(docid, docmodel); TempData["SelectedDepot"] = docmodel.DepotNo; TempData["SelectedDept"] = docmodel.DepartmentID; TempData["SelectedEmpID"] = 500; TempData["SelectedCatID"] = 100;
    message = "success";
    }
    catch (Exception ex)
    {
    message = ex.Message.ToString();
    }
    return Json(message); }

    DeleteEmpDoc.cshtml PartialView:

    @model WebApplication_core_test.Models.EmpDocsViewModel
    <script>
        function DeleteDocument(id) {
            $.ajax({
                type: "POST",
                url: "/EmpDoc/DeleteEmpDoc1?docid=" + id,
                dataType: "json",
                success: function (data) {
                    alert(data);
                    location.reload("/EmpDoc/EmpDocReIndex");
                },
                failure: function (response) {
                    alert("failure")
                    console.log(response.responseText);
                },
                error: function (response) {
                    alert("error")
                    console.log(response.responseText);
                }
    
            });
    
    
        }
    </script>
    
    <div class="col-sm-2">
        <div class="center-block ">
            <button type="button" id="btnDelete" class="btn btn-primary form-control" onclick="DeleteDocument(@Model.EmpDocID)">
                <i class="fa fa-save"></i><span class="padding-left-ten">Delete</span>
            </button>
        </div>
    </div>

    Here is the result of this work demo:

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 14, 2020 6:18 AM

All replies

  • User665608656 posted

    Hi polachan,

    By testing your code, I found some issues in it.

    First of all, in your Partial View cshtml code, you did not add an onclick event to the button, so the DeleteDocument event will never be triggered.

    Secondly, when you use Ajax to call the DeleteEmpDoc1 action method, you need to return the content to the success method of ajax instead of directly RedirectToAction to refresh the page.

    I recommend that you redirect to the EmpDocReIndex action in js in the ajax success method.

    In addition, you need to pass the docid value of the data deleted by the current click to the partial view, and then pass the onclick event as a parameter to the DeleteEmpDoc1 method.

    For details, please refer to the following code:

      [HttpPost]
            public JsonResult DeleteEmpDoc1(int docid)
            {
                string message = "";
    try
    { var docmodel = _unitOfWork.DocumentRepository.GetEmpDocumentsByID(docid); docmodel.IsDeleted = true; docmodel.DeletedBy = HttpContext.Session.GetInt32("UserID") ?? 0; docmodel.DeletedDateAndTime = DateTime.Now; long lideleted = _unitOfWork.DocumentRepository.Delete(docid, docmodel); TempData["SelectedDepot"] = docmodel.DepotNo; TempData["SelectedDept"] = docmodel.DepartmentID; TempData["SelectedEmpID"] = 500; TempData["SelectedCatID"] = 100;
    message = "success";
    }
    catch (Exception ex)
    {
    message = ex.Message.ToString();
    }
    return Json(message); }

    DeleteEmpDoc.cshtml PartialView:

    @model WebApplication_core_test.Models.EmpDocsViewModel
    <script>
        function DeleteDocument(id) {
            $.ajax({
                type: "POST",
                url: "/EmpDoc/DeleteEmpDoc1?docid=" + id,
                dataType: "json",
                success: function (data) {
                    alert(data);
                    location.reload("/EmpDoc/EmpDocReIndex");
                },
                failure: function (response) {
                    alert("failure")
                    console.log(response.responseText);
                },
                error: function (response) {
                    alert("error")
                    console.log(response.responseText);
                }
    
            });
    
    
        }
    </script>
    
    <div class="col-sm-2">
        <div class="center-block ">
            <button type="button" id="btnDelete" class="btn btn-primary form-control" onclick="DeleteDocument(@Model.EmpDocID)">
                <i class="fa fa-save"></i><span class="padding-left-ten">Delete</span>
            </button>
        </div>
    </div>

    Here is the result of this work demo:

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 14, 2020 6:18 AM
  • User-1355965324 posted
    Many Many Thanks for the help.
    Friday, February 14, 2020 4:29 PM