Trigger Bootstrap Modal using ASP Razor code within MVC Model value execution

I have a web application built with ASP .NET Core and MVC. The app features a side menu that allows the user to navigate through different pages based on their workflow. For example, when a user logs in for the first time, they are directed to the Home page where they can select HOME or LOGIN. If they choose LOGIN, an employee record is loaded and they are taken to the Employee View. Now, if the user tries to go back to the HOME page from the Employee View, I want to give them two options:

A) Sign out
B) Return to the Employee View

My plan was to implement this using a Modal Pop up. If the Employee exists, I would prompt the user to either sign out or return to the Home page. If the user chooses to sign out, I clear the Employee info and redirect them to the HOME page. If they choose to stay on the page, I take them back to the Employee View.

However, I am facing issues trying to trigger the Modal based on the state of the Employee object. I have tried various solutions from Stack Overflow, but none seem to work for me. While defining a button to open the Modal works, I cannot make it open dynamically based on the Employee state. Here's what my current INDEX.CSHTML looks like:

@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Http.Extensions
@model dynamic

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">      
</head>
<body>
    <!-- SET TO ALWAYS BE TRUE FOR TESTING -->
    @if (Model.Employee != null || Model.Employee == null)
    {
              <script type="text/javascript">
                $(document).ready(function() {
                 $("#exampleModal).modal("show");
                });          
              </script>
    }
    <!-- Button to open the modal COMMENTED OUT FOR NOW -->
    <!--  <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#exampleModal">
        Click Me!
    </button>  -->

    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
       <div class="modal-dialog">
         <div class="modal-content">
           <div class="modal-header">
             <h5 class="modal-title" id="exampleModalLabel">What Do You Mean Go Home?</h5>
             <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
           </div>
           <div class="modal-body">
             You are currently logged into the system.
             Would you like to Sign Off, or Go to Employee Page?
           </div>
           <div class="modal-footer">
             <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">EmployeePage</button>
             <button type="button" class="btn btn-primary">Sign Off</button>
           </div>
         </div>
       </div>
     </div>
    <!-- TEST CODE FOR MODAL BOOTSTRAP -->


    
<div class="container-fluid">
    <div class="row">
        <div class="col-2 bg-light border-right">
                <!-- Navigation menu -->
                @Html.Partial("_Lmenu")
            </div>
        <div class="col-10">
            <h1>Welcome to the Timeclock System</h1>
            <hr />   
            <div>
                    @if (!string.IsNullOrEmpty(Model.BZTNotes.MessageBody))
                    {
                        @Html.Raw(Model.BZTNotes.MessageBody)
                    }
            </div>
        </div>
    </div>
</div>
</body>
</html>

The app uses Bootstrap 5 for styling purposes.

Thank you in advance!

Answer №1

Firstly, make sure to include the closing " in your JavaScript code. Update your code as shown below:

$("#exampleModal").modal("show");

Additionally, do not forget to add the jQuery reference in your view:

<body>
    @*<script src="~/lib/jquery/dist/jquery.min.js"></script>*@       
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    
    <!-- SET TO ALWAYS BE TRUE FOR TESTING -->
    @if (Model.Employee != null || Model.Employee == null)
    {
        <script type="text/javascript">
            $(document).ready(function() {
             $("#exampleModal").modal("show");
            });
        </script>
    }
    //.....

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

What is the best way to create height segments from a cylinder in three.js?

My current project involves a cylinder that is divided into multiple height segments, with the number of segments depending on the specific data. Each height segment contains a value that I want to use for extruding the entire circle at that particular hei ...

Display text when hovered over or clicked to insert into an HTML table

I have an HTML table connected with a component field gameArray and I need it to: Show 'H' when the user's cursor hovers over TD (:hover) and the corresponding field in gameArray is an empty string, Fill the gameArray field after a click. ...

Unexpected patterns observed when utilizing parent/child routing files

I am working with a Node/Express backend that is implemented using TypeScript. Whenever I make changes to a file and save it, if I test the root route in Postman localhost:8000/, I receive the expected response. However, when I test localhost:8000/user af ...

Combining items from the identical array in pairs using distinct identifiers

I have an array containing double values. const data = [ -0.003,-8.178509172818559E-16, 0.002,-1.3576469946421737E-15, 0.007,-1.2329107629591376E-1] I am looking to utilize these values in react-vis. The necessary syntax for data insertion in react-vis ...

"Encountered an error with the code example for partitioning routes in Express.js

Note: For those who are new to this, there is an error in the Express documentation example. Make sure to include the next(); statement in your code like so: people.use(function(req, res, next) { next();//This line is necessary for the example to work ...

AngularJS: Issue with ng-show and ng-click not functioning when button is clicked

I have a specific requirement where I need to display and hide the description of each column in a table when a button is clicked. Here is the visual representation of what I have: the table In my HTML code, I have defined a button with ng-click as a func ...

Discovering the art of importing JavaScript files dynamically within controllers

I have one main form through which I pass data from 10 different components, each including the ID of a table that I need to retrieve data from in the database. The issue I am facing is that the code responsible for fetching this data asynchronously is spr ...

Modifying JavaScript using JavaScript

I'm looking for a solution to change the URL of a button in sync with the iframe displayed on the screen using JavaScript. The challenge I'm facing is figuring out how to dynamically update the button's URL based on the iframe content. Here ...

Utilizing Jquery Plugins in Node.js with ES6 Imports: A Comprehensive Guide

I recently started using a jQuery calendar plugin, which can be found at this link: . I have been utilizing it with a CDN, but now I am looking to incorporate it as a Node.js module. What would be the most effective method to achieve this? Edit: Just to ...

Synchronization Issue between Ionic Popover templateURL and Angular ng-model

In my project utilizing the Ionic framework, I encountered an issue with the code snippet below: $scope.loginCountryCode; $scope.loginPhone; // Code continues... <div class="container"> <label class="item item-input&quo ...

How can we calculate mesh positions and create a new Point3D object with specified coordinates (x, y,

private void BuildVertices(double x, double y, double len) { if (len > 0.002) { mesh.Positions.Add(new Point3D(x, y + len, -len)); mesh.Positions.Add(new Point3D(x - len, y - len, -len)); mesh.Positions.Add(new Point3D(x + len, y - len, -l ...

"Header background image gradually fades out and disappears as you scroll, revealing a bottom gradient effect in a React application

When I scroll, my header image fades away. I used JavaScript in my React app to achieve this effect: useEffect(() => { const handleScroll = () => { if (parallaxDiv.current) { parallaxDiv.current.style.backgroundPositionY = `${ ...

JavaScript Closures can utilize a shared global setting object or be passed as an argument to individual functions

Looking for advice on the use of a global "settings object" in relation to JavaScript closures. Should I access it from within functions in the global scope or pass the object every time a function requires access? To provide context, here's a mockup ...

The NextJS i18n feature is encountering an issue with the locale being undefined

Currently, I'm in the process of transitioning my website to NextJS, and I've run into some difficulties with internationalization. Even though I'm following the steps outlined in the official documentation, the locale displayed in the insp ...

What is the best way to configure AngularJS for optimal integration with Google Maps services and functionalities in an "angular way"?

I'm currently working on a new app that utilizes the Google distance matrix, directions service, and various map features such as custom markers. I'm curious - where do you think is the best place to house all of this different functionality? Sho ...

jQuery template does not respond to input text when a click event is enabled on an iPhone device

Below is a jQuery template I have: <div class="parent-class"> <div class="sub-class"> <div clas="sub-input-class"> <input type="text" /> </div> </div> </div> Recently, I ...

Learn the technique of storing a sequence of functions within a variable using jQuery

For instance, I am looking to assign a sequential process to multiple variables and utilize them in various scenarios. var disable_btn = true; var button_me = $('#contents.getsamplekit .sample-form .form #submit-btn-freeSample-me'); var button_d ...

Tips for effectively creating a fresh array of objects by extracting distinct values from arrays of child elements within a collection of parent objects

We have a requirement to extract data from objects structured like this: [ { "first": { "children" : [{ "name": "abc", "detail":"123"}, { "name": "def", "detail":"456"} ] }}, { "second": { "children" : [{ ...

Skipping certain key-value pairs during the conversion from JSON to Excel Worksheet using the XLSX library in JavaScript

I have a set of objects in JSON format within my JavaScript code and I am looking to transform this data into an Excel worksheet. Within the JSON structure, there are certain key-value pairs that I do not wish to include in the Excel output. For instance, ...

Tips for preventing Chrome from masking the background image and color on an autofill input

Google Chrome Browser has caused the background-color and background-image effects to be removed from the Username and Password input fields. Before autocomplete https://i.stack.imgur.com/Ww7Hg.png After autocomplete https://i.stack.imgur.com/hbG2C.png ...