Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello

I am self-teaching for a project so the problem might be fairly obvious.

I have a HTTP Post Method that is doing a database update.
On the event that there is an error, I want to return a view bag message to the Index page to populate a modal.
When I step through the code I can see the results are being passed ect but the Index page is not refreshing.

I have tried that many solutions I have lost count but this is the code I have at the moment. I also feel like im adding unnecessary steps now.
Some of it is hardcoded just now once i get this bit working im going to back and fix it.

Could someone please help?

What I have tried:

Razor
@if (ViewBag.ErrorMessage != null)
            {
                <div class="modal" tabindex="-1" role="dialog" id="errorModal">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content panel-warning">
                            <div class="modal-header" style="background-color:#f797a2">
                                <h5 class="modal-title">@ViewBag.ErrorTitle</h5>
    
                            </div>
                            <div class="modal-body">
                                <p>@ViewBag.ErrorMessage</p>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            }


JavaScript
var document = {};
                document.DisplayName = row.find(".DisplayName").find("span").html();
                document.FileComment = row.find(".FileComment").find("span").html();
                document.Order = row.find(".Order").find("span").html();
                document.Direction = row.find(".Direction").find("span").html();
                document.FileDate = row.find(".FileDate").find("span").html();
                document.Id = row.find(".Id").find("span").html();
                //customer.Country = row.find(".Country").find("span").html();
                $.ajax({
                    type: "POST",
                    url: "/Home/UpdateRecord",
                    data: '{document:' + JSON.stringify(document) + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        if (!response.success) {
                            alert(JSON.stringify(document));
                            alert(document.DisplayName);
                            $.ajax({
                                type: 'POST',
                                dataType: 'JSON',
                                url: '/Home/SetViewData',
                                data: { errorTitle:response.errorTitle, errorMessage: response.errorMessage },
                            });
                        }
                    },
                });
            });



C#
[HttpPost]
            public ActionResult UpdateRecord(ApplicationData_DocumentsModel document)
            {
                var record = _context.ApplicationData_Documents.Where(m => m.Id == document.Id).SingleOrDefault();
                if (record != null)
                {
                    try
                    {
                        _documentViewer.UpdateDocomentInfo(document);
                        ModelState.Clear();
                        return Json(new { success = true }, JsonRequestBehavior.AllowGet);
                        //return RedirectToAction("Index", new { year = record.Year, applicationRef = record.AppRef, type = record.Type, docRef = record.DocumentRef });
                    }
                    catch
                    {
                        ModelState.Clear();
                        return Json(new { success = false, errorTitle = "Unable to Update Record", errorMessage = "" }, JsonRequestBehavior.AllowGet);
                        //return View("Index", "Home", new { year = record.Year, applicationRef = record.AppRef, type = record.Type, docRef = record.DocumentRef });
                    }
    
                }
    
                ModelState.Clear();
                return Json(new { success = false, errorTitle = "Unable to Find Record", errorMessage = "" }, JsonRequestBehavior.AllowGet);
                //return View("Index", "Home", new { year = record.Year, applicationRef = record.AppRef, type = record.Type, docRef = record.DocumentRef });
            }




C#
public ActionResult Index(string year, string applicationRef, string type, string docRef = null)
            {
                
                bool documentRefremce = _documentViewer.DocumentRefrence(type);
    
                string path = documentRefremce == true ? $@"C:\Applications\Documents\{year}\{applicationRef}\{type}\{docRef}" 
                    : $@"C:\Applications\Documents\{year}\{applicationRef}\{type}";
    
               
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
    
                var documents = _documentViewer.GetDocumentsForMember(applicationRef, year, type, docRef);
                if(documents.Count == 0)
                {
                    documents.Add(new ApplicationData_DocumentsModel { Year = year, AppRef = applicationRef, Type = type, DocumentRef = docRef});
                }
    
    
                ViewBag.ErrorTitle = TempData["ErrorTitle"];
                ViewBag.ErrorMessage = TempData["ErrorMessage"];
    
                return documentRefremce == true ? View("BasicView", documents) : View(documents);
       
            }

C#
[HttpPost]
            public ActionResult SetViewData(string errorTitle, string errorMessage, string year = "2022", string appRef = "CLA708848977", string type = "Email", string documentRef = "") // hard coded for now
            {
                ViewBag.ErrorTitle = errorTitle;
                ViewBag.ErrorMessage = errorMessage;
                ModelState.Clear();
                return RedirectToAction("Index", new { year = year, applicationRef = appRef, type = type, docRef = documentRef });
            }
Posted
Updated 11-Feb-22 5:24am

1 solution

An AJAX request to the SetViewData action will not cause the current page to reload.

Also, the ViewBag only persists for the duration of the current request. By the time you've returned the "redirect" response, that information will be lost.

Change your UpdateRecord action to store the error details in the TempData slots already used by your Index action:
C#
[HttpPost]
public ActionResult UpdateRecord(ApplicationData_DocumentsModel document)
{
    var record = _context.ApplicationData_Documents.Where(m => m.Id == document.Id).SingleOrDefault();
    if (record is null)
    {
        TempData["ErrorTitle"] = "Unable to Find Record";
        TempData["ErrorMessage"] = "";
        return Json(new { success = false });
    }
    
    try
    {
        _documentViewer.UpdateDocomentInfo(document);
        TempData.Remove("ErrorTitle");
        TempData.Remove("ErrorMessage");
        return Json(new { success = true });
    }
    catch (Exception ex)
    {
        TempData["ErrorTitle"] = "Unable to Update Record";
        TempData["ErrorMessage"] = ex.Message;
        return Json(new { success = false });
    }
}

Then update your Javascript to reload the current page if the AJAX request fails:
JavaScript
const document = {
    document: {
        DisplayName = row.find(".DisplayName").find("span").html(),
        FileComment = row.find(".FileComment").find("span").html(),
        Order = row.find(".Order").find("span").html(),
        Direction = row.find(".Direction").find("span").html(),
        FileDate = row.find(".FileDate").find("span").html(),
        Id = row.find(".Id").find("span").html()
    }
};

$.ajax({
    type: "POST",
    url: "/Home/UpdateRecord",
    data: document,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        if (!response.success) {
            // Reload the current page to show the error:
            location.reload();
        }
    },
});
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900