Ways to show notifications multiple times depending on the number of items in a list

My task is to show banner messages on the user interface based on the number of items in a list.

In my _Layout file, I called my partial view like this:

@Html.Partial("~/_Notification.cshtml")

The content of _Notification.cshtml:


    <div id="outage-notification" class="row" style="display: none;">
        <div>
            <div>
                <div id="notification-content" class="notification-content"></div>
                <div class="dismiss-notification"><a class="small noloader" href="javascript:void(0);">@CommonUIResources.Dismiss</a></div>
            </div>
        </div>
    </div>
@Scripts.Render("~/bundles/outageNotification")

My JavaScript file:


var outageNotification;
class OutageNotification {
    constructor() {
        this.setup();
    }
    setup() {
        var date1 = new Date().toUTCString();
        $.ajax({
            type: "GET",
            url: "Notification/GetBannerNotifications",
            data: { dateTime: date1 },
            success: function (notificationMessage) {
                if (notificationMessage !== undefined && notificationMessage !== "") {
                    $("#notification-content").append(notificationMessage);
                    $("#notification").fadeIn("slow");
                }
                else {
                }
            }
        });
    }
}
$(document).ready(() => {
    this.outageNotification = new OutageNotification();
});

My Controller method:


[HttpGet]
[Route("Notification/GetBannerNotifications")]
public JsonResult GetBannerNotifications(DateTime? dateTime)
{
    var listOfStrings = this.notificationService.GetBannerNotifications(dateTime.Value);
    return this.Json(listOfStrings, JsonRequestBehavior.AllowGet);
}

Output: https://i.sstatic.net/fgXjO.png

The image below only contains one string, but even if there are multiple strings, it shows all of them in one image.

It merges all the strings into a single string and displays that on the UI.
However, I want to display this image multiple times depending on the number of strings in the list.

Answer №1

It is currently consolidating all the strings into a single string and displaying that in the user interface. However, I am looking to display this image multiple times based on the number of strings in the List.

If the GetBannerNotifications action method returns a list of strings, you will receive a json array from the response data on the JavaScript client side as shown below:

["ohello1 1/14/2021 12:00:00 PM-1/14/2021 12:30:00 PM","ohello2 1/15/2021 12:00:00 PM-1/15/2021 12:30:00 PM"]

To meet your stated requirement, you can iterate through the received json array data and dynamically display your outage-notification widget.

var date1 = new Date().toUTCString();
$.ajax({
    type: "GET",
    url: "Notification/GetBannerNotifications",
    data: { dateTime: date1 },
    success: function (notificationMessage) {
        if (notificationMessage !== undefined && notificationMessage !== "") {

            console.log(notificationMessage);

            $("#notification-content").html(notificationMessage[0]);

            $.each(notificationMessage, function (i, mes) {
                if (i > 0) {
                    console.log(mes);

                    //logic implementation here depending on the plugin being used

                    //the following code snippet is for testing purposes using fadeIn and fadeOut animation
                    $("#outage-notification").fadeIn(5000, function () {
                        $("#outage-notification").fadeOut("slow");

                        $("#notification-content").html(mes);
                    });
                }                        

            })

        }
        else {
        }
    }
});

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

Encountering a POST 504 error while attempting to proxy an Angular application to a Node server

error message: Failed to connect to http://localhost:4200/api/user/login with a 504 Gateway Timeout error. Encountered this issue while attempting to set up a login feature in my Angular application and establish communication with the Express backend. Th ...

Tips for retrieving JSON data from an AJAX call and displaying it pre-filled in an input field

Here is the code snippet I used to receive a response in JSON format, but when I try to display the response using alert(response.Subject);, it shows as "undefined". HTML: <input type="text" id="subject" value='Subject'> Javascript: $.a ...

PHP website freezes unexpectedly in Firefox version 4

For over a year, our website has been functioning perfectly. However, with the release of Firefox4, we have noticed a new issue. Occasionally, the page hangs randomly. I have tested the website on IE8/9, Chrome10+, Safari, and Opera, and the issue only see ...

Testing Angular 16 Component with Jasmine Spy and callFake Strategy

I've encountered an issue while trying to test my component unit. The problem arises when I call the product-list.component.ts from my product.service.ts. While my product.service.spec.ts is successful, the product-list.component.spec.ts fails as the ...

The img-wrapper is failing to show the PNG image

I'm having an issue with my code where it displays jpg images but not png. How can I make the img-wrapper show png files as well? In my example, the first image in the array is a jpg while the second is a png. However, I only see the title of the imag ...

Guide on how to trigger a pop-up modal to open a new webpage by clicking on a hyperlink

I have a page called one.html that has a link on it <a href="#">Click to open second page<a/> When this link is clicked, I would like for second.html to open in a popup modal. The second page contains a basic table that I want to di ...

express-validator: bypass additional validation in a user-defined validator

Utilizing the express-validator package for validating my request data. As per the documentation, we need to declare them in this manner: app.use(expressValidator({ customValidators: { isArray: function(value) { return Array.isArray(value); ...

"Error: Discord Js encounters an issue trying to access the titles property of an

Having trouble with a random number generator in my discord bot. Whenever someone enters +nhr, it may work or display an error message in the console: TypeError: Cannot read property 'titles' of undefined and Unhandled promise rejection. Thi ...

What is the proper way to implement BufferList with SocketAsyncEventArgs to avoid encountering the SocketError InvalidArgument?

Using SetBuffer with SocketAsyncEventArgs is working well for me. However, whenever I attempt to utilize BufferList (after setting the buffer to null) and then call SendAsync on the socket, I consistently encounter the SocketError InvalidArgument (10022) ...

There appears to be an issue with the express Router when trying to access the '/page' route

Currently, I am in the process of creating a basic express routing system while utilizing vanilla HTML for the front-end. index.js const express = require('express'), bodyParser = require('body-parser'), serverle ...

Modifying a variable within the return statement in a React Native component

I am relatively new to React and React-native and I am facing challenges in understanding how to update a variable within the return method. Here is my current code snippet: import React, { Component } from "react"; import { View, StyleSheet, Platform, T ...

Activate the click action within the option directive

I'm trying to activate a click event when options are clicked instead of using the change event for specific reasons. Below is my code snippet: .directive('itemOptions', [ function() { return { ...

Having trouble running a form due to the inclusion of JavaScript within PHP code

My PHP code includes a form that connects to a database, but when I add JavaScript to the same file, the form does not execute properly. (I have omitted the insert code here.) echo '<form action="$_SERVER["REQUEST_URI"];" method="POST">'; ...

Syntax for the RangeValidator in the Enterprise Library

I want to implement the Enterprise Library RangeValidator attribute in order to validate that a decimal value is greater than zero: <RangeValidator(GetType(Decimal), "0.00", RangeBoundaryType.Exclusive, "1", RangeBoundaryType.Ignore, "MyMessage", "", N ...

I am having trouble getting my website to work offline using caching

My cache file is displayed below: CACHE MANIFEST # 2013-11-22 14:38:54735779 CACHE: ../../../../assets/img/background_01.jpg ../../../../assets/img/background_02.jpg ../../../../assets/img/background_03.jpg ../../../../assets/img/datepicker_icon.png .. ...

Verify if the dates align in javascript

I am currently in the process of developing a custom ASP.Net validator that verifies whether the input data corresponds to a non-working day. For the purpose of this validation, a "non-working day" is defined as follows: The date falls on either a Satur ...

Utilizing Mysql Database Information in a JavaScript Widget

I am in the process of developing a widget that users can add to their blogs in order to drive traffic to my coupon code website. The goal is for the widget to retrieve information from the database and display the top 5 coupons of the day. This is what I ...

Combine and inject global SCSS file into all components using browserify and vueify

When developing an app, I utilize browserify along with vueify. My goal is to inject a global SCSS file containing variables, mixins, colors, etc., into Vue so that it is accessible to all components without the need for explicit import statements in each ...

Input text fields are restricted to only accept numerical values

I recently tried out the Jquery Numeric plugin, but unfortunately I discovered that it does not work on FireFox 3.6 on OSX as it does not allow pasting. Therefore, I am in search of a different Jquery plugin or Javascript snippet that specifically allows ...

Transferring data from JavaScript to PHP for geolocation feature

Hello everyone, I'm looking to extract the longitude and latitude values from my JavaScript code and assign them to PHP variables $lat and $lng. This way, I can retrieve the city name and use it in my SQL query (query not provided). Below is the scrip ...