Troubleshooting: Bootstrap Modal in .NET MVC not appearing on screen

Below is the code that manages order quotes and includes an if statement. The objective is to display an error message using TempData and Bootstrap Modal if the product quantity in the order exceeds the stock quantity. However, despite TempData not being null, the modal does not show up when testing. This technique is used in other areas of the project with success, but for some reason it's not working here. Below is the related action:

public async Task<IActionResult> ManageOrderQuote(int orderId, string status, string statusDescription)
{
    var order = await orderQuote.GetByIdAsync(orderId);
    var orderDetails = await orderQuoteDetail.GetAllByIdAsync(orderId);
    foreach (var detail in orderDetails)
    {
        var productId = detail.ProductId;
        var productToUpdate = await product.GetByIdAsync(productId);
        productToUpdate.UnitsOnOrder += detail.Quantity;
        
        productToUpdate.UnitsInStock -= detail.Quantity;
        if (productToUpdate.UnitsInStock < 0)
        {
            TempData["ErrorMessage"] = "The " + productToUpdate.ProductName + " product doesn't have enough stock.";
            
            return RedirectToAction("PendingOrders");
        }
        await product.UpdateAsync(productToUpdate);
    }
    
    order.Status = status;
    order.StatusDescription = statusDescription;
    await orderQuote.UpdateAsync(order);

    return RedirectToAction("PendingOrders");
}

JS code and the modal:

@if (TempData["ErrorMessage"] != null)
{
    <script>
        $(document).ready(function () {
            $('#errorModal').modal('show');
        });
    </script>
}

<!-- Error Modal -->
<div class="modal fade" id="errorModal" tabindex="-1" aria-labelledby="errorModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-light">
                <h5 class="modal-title" id="errorModalLabel">Error</h5>
            </div>
            <div class="modal-body">
                <p class="text-danger">@TempData["ErrorMessage"]</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

This is the AJAX call:

 $('#statusForm').submit(function (e) {
     e.preventDefault();
     var orderId = $('#orderId').val();
     var status = $('#status').val();
     var statusDescription = $('#statusDescription').val();
     $.ajax({
         url: '/Sales/ManageOrderQuote',
         type: 'POST',
         data: {
             orderId: orderId,
             status: status,
             statusDescription: statusDescription
         },
         success: function (response) {
             $('#statusModal').modal('hide');
             
             $('.modal-backdrop').remove();
             window.location.reload();             
         },
         error: function () {
             alert('An error occurred while changing order status.');
         }
     });
 });

PendingOrders.cs:

public async Task<IActionResult> PendingOrders()
{
    var orders = await orderQuote.GetAllPendingOrders();

    var orderList = new List<OrderVM>();
    foreach (var order in orders)
    {
        var orderVM = new OrderVM()
        {
            OrderQuoteId = order.OrderQuoteId,
            
            CustomerName = order.Customer?.ContactFirstName + " " + order.Customer?.ContactLastName,
            
            OrderDate = order.OrderDate,
            Status = order.Status,
            StatusDescription = order.StatusDescription
        };
        orderList.Add(orderVM);
    }
    return View(orderList);
}

Answer №1

If we want to display a modal using AJAX, we can follow these steps:

1. Insert

<div id="divToUpdated"></div>
into the page and make an AJAX call to trigger the modal.

2. Update the ajax success function as shown below:

success: function (response) {
     $('#statusModal').modal('hide');
     $('.modal-backdrop').remove();
     // window.location.reload();
     $("#divToUpdated").html(response);
 },

Please note: This will display the PendingOrders page along with the modal dialog.

Alternatively, apart from steps 1 and 2, we can utilize a PartialView to render the modal. By putting the necessary JS code and modal content in a PartialView named _modalPartialView, we can include it like this:

if (productToUpdate.UnitsInStock < 0)
        {
            TempData["ErrorMessage"] = "The " + productToUpdate.ProductName + " product doesn't have enough stock.";
           return PartialView("_modalPartialView");
        }

Result:

https://i.sstatic.net/03k94.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Column Reordering in DataTable Causes Data to be Mapped Incorrectly

I have created a JSBin where you can view the code. However, due to CORS policy restrictions, the ajax URL I used is not functioning properly. The output generated shows that the data is mapped incorrectly in the columns. Can someone please help me figure ...

Error: The method By.cssSelector is invalid and cannot be used

Currently utilizing npm's Selenium Webdriver. Having difficulty getting By.cssSelector to function properly. Other selectors like By.tagName and By.id are working fine. Here is the code snippet: var webdriver = require('selenium-webdriver&apos ...

SCORM: moving between SCOs by clicking a button in the presentation

Currently, I am developing a website that allows users to create presentations. One of the website's features is the ability to export presentations in SCORM format (either 1.2 or 2004). This is my first time working with SCORM and I am currently impl ...

AngularJS and KendoUI integration experiencing delays during script evaluation

At the moment, I am conducting performance measurements and analysis on our AngularJS-KendoUI application in an effort to identify any bottlenecks. Following a helpful article and an informative presentation, I am using Chrome DevTools timeline tab to anal ...

Combining edit and view functionalities in jqGrid form

I've been exploring the jqGrid wiki but I'm having trouble finding answers to a couple of things. It seems like it might be too customized. 1) Can jqGrid be configured to display all fields of a row when editing via form edit, but only make a fe ...

Soap client error: InvalidOperationException raised

I have successfully added a WSDL file using the "Add Service Reference" dialog in Visual Studio 2008. MyService serviceproxy = new MyService(); Upon instantiating the service proxy, I encountered an InvalidOperationException with the following message (t ...

How can you determine the specific type of "display" utilized by CSS Bootstrap for a particular element?

When manipulating the "display" property of a bootstrap element like "row" or "col-md-3" using JavaScript, how can I determine the default value set by Bootstrap CSS? For instance, the Bootstrap source code likely sets the "display" value for the "row" cl ...

What is the best approach to configure Nuxt.js to recognize both `/` and `/index.html` URLs?

Currently, I have set up my Nuxt.js in default mode with universal and history router configurations. After running nuxt generate, the generated website includes an index.html file in the dist folder. This means that when the website is published, it can ...

Learn how to access the `$root` instance in Vue.js 3 setup() function

When working with Vue 2, accessing this.$root is possible within the created hook. However, in Vue 3, the functionality that would normally be placed within the created hook is now handled by setup(). The challenge arises when trying to access properties ...

display or conceal a div when a radio button is selected

I need a way to display a specific div containing unique text once a radio button is selected, while hiding all other div sections. <?php foreach ($items as $item){ $i=1; echo ' <div class="form-check"> <input class="fo ...

issues arising with React and the "this" keyword persist even after implementing binding

[UPDATE] I've encountered an issue where, in ListItem.js, when attempting to console log this.props (with or without passing props to the constructor), all props aside from the method are displayed. Even after removing the entire onchange event from L ...

Exploring the differences between scoping with let and without any scoping in

Within my code, there is a forEach loop containing a nested for loop. It's interesting that, even though I have a statement word = foo outside of the for loop but still inside the forEach loop, I can actually log the value of word after the entire for ...

Reactjs is failing to display the page

I am facing an issue where the components are not rendering in the browser even though there is no error being displayed. This makes it difficult to troubleshoot and resolve the problem. Can someone help me identify the root cause? import React, { Com ...

JavaScript, detecting repeated characters

I need to create a script that checks an input box (password) for the occurrence of the same character appearing twice. This script should work alongside existing regex validation. I believe I will need to use a loop to check if any character appears twice ...

Is it possible for setTimeout to not increment the counter in node.js?

Even though the loop is executed multiple times in the Node.js program below, why does the control not exit the loop? I made sure to increment the value of i within setTimeout instead of forgetting to do i++ in the for loop. function abc () { for(var ...

Choose JSON information and modify it utilizing NODE.js with identical data

Feeling stuck.. I have a JSON file with some data and I need to manipulate it. Take a look at my JSON structure: [{ "method": "GET", "path": "/", "aliases": "", "name": "rootPath", "handler": "generatedApps/avion01/actions.HomeHandler" }, { "method": "GET ...

The Ajax script triggers the PHP script twice

Utilizing AJAX on my HTML page, I am able to dynamically load data from a MySQL database without reloading the page and send email notifications upon certain events. The process involves Ajax calls to script.php which then makes requests to the database an ...

Secure User Authentication using HTML and JavaScript Box

In the given code, I am attempting to implement a functionality where a message is displayed next to the select box if it does not have a value of male or female. This message should not be shown if one of these values is selected. However, this feature ...

div added on the fly not showing up

I'm attempting to dynamically add a div to a webpage using Chrome. Despite following several instructional guides, the code does not seem to be working as expected. I have added style attributes to make it more visible, but the element is not showing ...

locating the truth value of the data in an array retrieved from MongoDB

When returning from the mongoose find() function, I need to ensure that is_reqestor = true is checked. However, when updating the document, I pass the id which needs to be updated. let filter = { is_reqestor: true } if (!is ...