What is the most effective way to implement a single modal throughout my web application without having to duplicate HTML code on each page?

After realizing I was repetitively adding the same div to every page for a modal dialog, I decided to place a single div in the site.master page and call it when needed. This method worked fine until I began implementing ajax with partial page updates. How can I prevent having to include dialog html in each update panel?

Answer №1

After dedicating the past few days to developing a single-source modal function that can be shared across applications as a DLL, I am grateful for the community's support and guidance along the way. Here is my comprehensive solution, hoping it proves beneficial to others.

This particular solution eliminates the need for JavaScript by utilizing the :target CSS pseudo-class to close the modal.

In the site.master file, insert a placeholder:

<asp:PlaceHolder ID="phModalDialog" runat="server" />

Next, create a new class file:

Public Class SiteModal

Public Enum msgLevel
    message_info = 0
    message_warning = 1
    message_error = 2
    message_success = 3
End Enum

Public Shared Sub showModalMsg(ByVal sMsg As String,
                               Optional ByVal container As Control = Nothing,
                               Optional ByVal Level As msgLevel = 0,
                               Optional ByVal customHeaderTitle As String = "Information")

    ' Dialog site-wide
    ' NOTE: Call can pass custom header text if desired
    Dim sClass As String = "message_info"
    Select Case Level
        Case 0
            If String.IsNullOrEmpty(customHeaderTitle) Then
                customHeaderTitle = "Information"
            End If
        Case 1
            sClass = "message_warning"
            If String.IsNullOrEmpty(customHeaderTitle) Then
                customHeaderTitle = "Caution"
            End If
        Case 2
            sClass = "message_error"
            If String.IsNullOrEmpty(customHeaderTitle) Then
                customHeaderTitle = "Error"
            End If
        Case 3
            sClass = "message_success"
            If String.IsNullOrEmpty(customHeaderTitle) Then
                customHeaderTitle = "Confirmation"
            End If
    End Select

     Dim pnl As New Panel
    pnl.ID = "pnlGlobalModal"
    pnl.CssClass = "modal-dialog"
    Dim pnl2 As New Panel
    Dim lbtn As New HyperLink
    lbtn.ID = "lbtnModalDialogClose"
    'lbtn.NavigateUrl = "#MainContent_pnlGlobalModal" '& pnl.ClientID
    lbtn.CssClass = "modal-close-btn"
    Dim lbl As New Label
    lbl.ID = "lModalHeading"
    lbl.CssClass = "modal-header"
    lbl.Text = customHeaderTitle
    Dim lbl2 As New Label
    lbl2.ID = "lModalMessage"
    lbl2.CssClass = sClass
    lbl2.Text = "<br>" & sMsg
    'Assemble
    pnl2.Controls.Add(lbl)
    pnl2.Controls.Add(lbl2)
    pnl.Controls.Add(pnl2)
    pnl2.Controls.Add(lbtn)

    If container IsNot Nothing Then
        ' Load inside update panel/container if provided (ajax)
        container.Controls.Add(pnl)
        lbtn.NavigateUrl = "#" & pnl.ClientID
    Else
        ' Load inside placeholder on Master Page  (full postback)
        Dim pageHandler = HttpContext.Current.CurrentHandler
        If TypeOf pageHandler Is System.Web.UI.Page Then
            Dim ph As PlaceHolder = DirectCast(pageHandler, System.Web.UI.Page).Master.FindControl("phModalDialog")
            If ph IsNot Nothing Then
                ph.Controls.Add(pnl)
                Dim path As String = HttpContext.Current.Request.Url.AbsolutePath
                lbtn.NavigateUrl = path & "#" & pnl.ClientID
            End If
        End If

    End If
 End Sub

End class

Moreover, here is the accompanying CSS code utilizing the :target to conceal the modal:

.modal-dialog{
position: fixed;
font-family: Arial, Helvetica, sans-serif;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0,0,0,0.8);
z-index: 99999;
opacity:1;
-webkit-transition: opacity 400ms ease-in;
-moz-transition: opacity 400ms ease-in;
transition: opacity 400ms ease-in;
}

.modal-dialog:target {
   visibility:hidden;
}

.modal-dialog> div {
width: 400px;
position: relative;
margin: 10% auto;
padding: 5px 20px 13px 20px;
border-radius: 10px;
background: #fff;
background: -moz-linear-gradient(#fff, #999);
background: -webkit-linear-gradient(#fff, #999);
background: -o-linear-gradient(#fff, #999);
 }

.modal-close-btn {
    background: #606061;
color: #FFFFFF;
line-height: 25px;
position: absolute;
right: -12px;
text-align: center;
top: -10px;
width: 24px;
text-decoration: none;
font-weight: bold;
    cursor:pointer;
-webkit-border-radius: 12px;
-moz-border-radius: 12px;
border-radius: 12px;
-moz-box-shadow: 1px 1px 3px #000;
-webkit-box-shadow: 1px 1px 3px #000;
box-shadow: 1px 1px 3px #000;
}

.modal-close-btn:hover { background: #00d9ff; }

.modal-close-btn::before {
    content: "\2716";
}

To demonstrate how to use this functionality:

      ModalDialog.showModalMsg("test message", , ModalDialog.msgLevel.message_info, "CUSTOM HEADER")

If calling from an update panel, provide the container ID like so:

      ModalDialog.showModalMsg("test message",mypanelID , ModalDialog.msgLevel.message_info, "CUSTOM HEADER")

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

Tips for adjusting the width of an li element based on the width of its longest content

My database dynamically populates an unordered list with content, utilizing the following code in the back end: StringBuilder output = new StringBuilder(); int lastDepth = -1; int numUL = 0; foreach (DataRow row in dt.Rows) { ...

Encountering an issue with postman where properties of undefined cannot be read

I am facing an issue while trying to create a user in my database through the signup process. When I manually enter the data in the create method, it works fine as shown below: Note: The schema components are {userName:String , number:String , email:Stri ...

Horizontal expanding and collapsing navigation menu

Is there a way to modify the expand menu bar so it expands from left to right or right to left, instead of top down? Any assistance would be greatly appreciated. Existing Expand Menu Bar <HTML> <HEAD> <META http-equiv="Content-Type" c ...

Exploring the Potential of JSP in Form Submissions

Here's a OCWCD question that I encountered: <form action="sendOrder.jsp"> <input type="text" name="creditCard"> <input type="text" name="expirationDate"> <input type="submit"/> </form> The question based on the ...

Having trouble deleting element despite having the correct ID?

Whenever I click on the map, it adds an element to the map div using this line of code: $('#map').append('<label>test:</label><input type="hidden" name="map_coords" id="' + e.latlng.lat + '" value="' + e.latlng ...

What methods can I use to adjust link distance while using the 3d-force-graph tool?

Exploring the capabilities of the 3D Force Graph from this repository has been an interesting journey for me. I am currently seeking ways to adjust the bond strength between nodes. I am specifically looking to modify either the link width or length, but ...

CSS Grid with dynamically changing number of rows set to "auto", while ensuring one row always has a fixed size of "1fr"

Currently, I am experimenting with a CSS grid-based frontend and have encountered a specific requirement that keeps repeating itself in various parts of the frontend: A grid with a dynamic number of rows. Each row should be of variable size (auto). The f ...

Passing a Typescript object as a parameter in a function call

modifications: { babelSetup?: TransformationModifier<babel.Configuration>, } = {} While examining some code in a React project, I came across the above snippet that is passed as an argument to a function. As far as I can tell, the modifications p ...

Executing a JavaScript function when an HTML page is loaded within an OBJECT Tag

I have a situation where I am loading an HTML page inside an object tag. Since the iPad does not support iFrames, I decided to use the object tag to load external HTML pages into a container. Everything is working well so far, but now I want to be able t ...

Combining filters with AJAX, PHP, and MySQL for seamless interaction

I've been working on a table that displays a list of users, and I'm trying to implement filters using select boxes to refine the results based on certain parameters. The table is generated dynamically through a PHP script triggered by AJAX when t ...

Managing modules within the node_modules folder that have dependencies on .css files

Currently, I am involved in a project where we are utilizing a custom UI library that includes some dependencies. These components come with their own corresponding .css files. The structure of the source code looks like this: |- src |-| |- components ...

Looking for guidance on integrating cookies with express session? Keep in mind that connect.sid is expected to be phased out

Within my app.js file, I have the following code snippet: app.use(session({secret: 'mySecret', resave: false, saveUninitialized: false})); While this setup functions correctly, it triggers a warning message: The cookie “connect.sid” will ...

Steps for accessing data from AWS API Gateway and showcasing it on a static website stored on S3

I am in the process of sending an ajax request to AWS API Gateway to extract data from a JSON and display it on a webpage. The objective is to have a webpage load, trigger an ajax request to API Gateway, which then invokes a lambda function to fetch inform ...

How can I modify the URL path using react-i18next?

I've been grappling with this problem for the past few days. My React app is causing me some trouble as I try to implement multilingual support using i18next. I aim to modify the URL path based on the selected language, such as http://localhost:3000/e ...

Can Ajax be utilized to call a PHP script that contains another Ajax function?

I have set up a checkbox that triggers an Ajax call to another PHP script once checked. In this PHP script, there are three text boxes and a button. When the button is pressed, another Ajax call is made to execute yet another PHP script, all within the sam ...

SQL Sorting Investigation

I am working with a SQL table that contains a column called reference_number. The values in the reference_number column follow the format of x-MMYY-xxxx. (MM represents the month and YY stands for year. -xxxx indicates auto-increment.) My current challen ...

What is the best way to dynamically shift the position of an image on a page while keeping it in place in real-time?

A group of friends and I are currently collaborating on an experimental project for a presentation. Our goal is to have multiple elements (such as images, text, gifs) displayed on a page that can be dragged around in real-time using a draggable script whi ...

Adjust the size of a canvas using JavaFX in an FXML file

I am encountering an issue with resizing a canvas in Javafx while using scene builder and fxml. Currently, when the user clicks on the canvas, it turns black, but upon resizing the screen and clicking on the canvas again, only the original size of the canv ...

What's the significance of this issue? Fatal error: Inability to utilize function return value in write context

An error occurred while processing the PHP code Severity: Compile Error Message: Unable to use function return value in write context line number:116 floor($BudgetPerPerson) = $TotalBudget / $NumberOfPeople; label class="heading">What ...

Having difficulties redirecting with the button's onclick function

I'm struggling to redirect users to another page using a button (assuming the hostname is localhost:8000) $('#getFruit').attr('onclick', window.location.host + '/getFruit/banana') <script src="https://cdnjs.cloudfl ...