Guide on switching the theme color in c# aspnet core using a toggle button within a partialview

Description

I am looking to change the color scheme of my Bootstrap 5.3 theme by clicking a button within a partial view.

The toggle button is customized to meet my specific requirements, and the chosen value is stored in a cookie for future reference.

This partial view will be integrated into the navigation menu.

Despite extensive efforts, I have not been able to find a suitable solution for this particular scenario.

Query

What is the correct approach to implementing this functionality?

Code snippet from the partial view

@{

static void ToggleTheme()
{
    string bg = HttpContext.Request?.Cookies["mybg"]?.ToString();

    if (bg == "light" || bg == null)
    {
        HttpContext.Response.Cookies.Delete("mybg");
        HttpContext.Response.Cookies.Append("mybg", "dark");
    }
    else
    {
        HttpContext.Response.Cookies.Delete("mybg");
        HttpContext.Response.Cookies.Append("mybg", "light");
    }
}

}

<button type="submit" name="submit" class="btn btn-sm btn-outline-light" onclick="ToggleTheme()">

Theme

Answer №1

Here is a demonstration that you can easily follow:

Partial View (located in Pages/Shared or Views/Shared folder)

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
@{
    // Retrieve the current theme preference from the cookie
    string currentTheme = HttpContextAccessor.HttpContext.Request?.Cookies["mybg"]?.ToString();
}
<button type="submit" name="submit" class="btn btn-sm btn-outline-light" onclick="ToggleTheme()">ChangeTheme</button>
<script>
    // Function to switch between themes and store the preference in a cookie
    function ToggleTheme() {
        var currentTheme = document.body.classList.contains('theme-dark') ? 'light' : 'dark';

        // Switch the theme class on the body element
        document.body.classList.toggle('theme-dark');

        // Store the theme preference in a cookie
        document.cookie = "mybg=" + currentTheme + "; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
    }

    // Set initial theme based on the cookie value
    window.onload = function () {
        var currentTheme = "@currentTheme";
        if (currentTheme === "dark") {
            document.body.classList.add('theme-dark');
        }
    };
</script>
<style>
    .theme-dark {
        background-color: #1f1f1f; /* Dark background color */
        color: #ffffff; /* Light text color on dark background */
        /* Additional styles for dark-themed elements */
    }
</style>

Layout

<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
    <div class="container">
        <a class="navbar-brand" asp-area="" asp-page="/Index">IdentityProj8</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
            <ul class="navbar-nav flex-grow-1">
                <li class="nav-item">
                    <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
                </li>
            </ul>
            <partial name="_Partial" />
        </div>
    </div>
</nav>

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

How can I pass my cookie token in a Next.js server-side component request?

My Next.js version is 14.1.0 and I am currently using the App router. async function Page() { const dataPromise: Promise<any> = getData(); const data = await dataPromise; console.log('data: ', data); return ( .... ); } The ge ...

Attempting to showcase the data stored within MongoDB documents on my website's user interface

I am facing difficulties in showing the data stored in my database on the front end of my grocery list app, which is built using the MERN stack. I have a form that successfully sends data to MongoDB and saves it upon submission. In order to retrieve the d ...

Converting Database Information to JSON Format for Mobile Authentication Form

Currently, I am working on a Mobile App project using Phonegap that requires users to log in before retrieving JSON data. This PHP page is responsible for connecting to the mobile site and fetching the necessary information. <?php $con = mysqli_connec ...

Is there a way to ensure my chat view functions properly without relying on partial views?

I am currently working on integrating a private chat feature using SignalR in my project, and I have encountered an issue while creating a View with accessible model values to pass to the server. Specifically, I have a list of doctors, and when a user clic ...

Using jQuery to fetch data asynchronously

I am currently dealing with a web application that needs to carry out the following task. It must send GET requests to a web service for each date within a selected date range, yet this process can be time-consuming. Since I plan to visualize the retrieved ...

Encountering issues with returning values correctly when using module.exports in Node.js

function userLogin(username, password) { var status; var userid = username; User.findOne({ 'username': [userid], 'password': [password] }, function(err, user) { if (!user) { console.lo ...

Enhance the Angular KendoGrid excelExport feature with a custom column addition event

When utilizing the excelExport event in KendoGrid to modify certain column data before exporting it, is there a way to insert a new column between two existing columns? Here's the current code I'm using to manipulate dates. I would like to add a ...

The function e.preventDefault() appears to be ineffective when applied to both the submit button and anchor tag within an

In my ASP.Net Core MVC App View <form> <div class="container"> <div class="row"> <div class="col-md-offset-2 col-md-4"> <div class="form-group"> <input type="text" class="form-contr ...

Ways to quickly terminate a pipeline in a JavaScript transformation

Issue: I am facing a challenge with handling large files (>10GB). At times, I need to process the entire file while other times I only need to sample a few lines. The processing mechanism involves a pipeline: pipeline( inStream, ...

Plugin for creating a navigation bar with a jQuery and Outlook-inspired style

Our team is considering transitioning our asp.net forms application to MVC. Currently, we utilize outlook-style navigation with ASP controls such as listview and accordion, using code referenced here. Are there any jQuery/CSS controls available for MVC t ...

Accessing the Angular scope and making modifications using Chrome browser

I need to access the $scope value in order to update its data values via a chrome extension. I have attempted to obtain the $scope using the code below: var $scope = angular.element(document.getElementById('name')).scope() While this code wor ...

Ways to navigate through a webpage without encountering any overflow issues

My window is too small to scroll, but I still need the ability to do so. Is it possible to scroll even when the height of the container is not large enough to display the scrollbar? Below is the code I am using to achieve scrolling: setTimeout(function() ...

Challenge with Angular *ngFor: Struggling to Access Previous Elements

In my angular and node application, I am using socket.io. When a user joins the room, they can see their username in the user list. If another user joins, the first user can see both usernames but the new user can only see their own. This pattern continues ...

When using Vuejs + Laravel to make an Ajax request, only the most recent information entered into the view is submitted

Can someone guide me on implementing a basic ajax request using Vue with my Laravel backend? I have a boolean field called completed in a table named courses. In the view, users can see all assigned courses and toggle their completion status by pressing a ...

Convert the existing JavaScript code to TypeScript in order to resolve the implicit error

I'm currently working on my initial React project using Typescript, but I've hit a snag with the code snippet below. An error message is popping up - Parameter 'name' implicitly has an 'any' type.ts(7006) Here is the complet ...

Is it possible to showcase a dropdown list within a constantly changing table?

I have a table code snippet that I need help with <fieldset class="tabular"><legend><%= l(:redmine_taskjuggler) %></legend> <%= labelled_fields_for(@issue) do |f| %> <div id="taskjuggler" class="attributes"> <div cl ...

Error: A SyntaxError was encountered due to a missing closing parenthesis after an argument list while writing JavaScript within PHP code

I'm facing an issue writing JavaScript within PHP code. Here's my script : echo ' <script>'; echo ' $(function(){'; echo ' x = parseInt($("#counter2").val());'; echo ' $("#add_row2").click(function(){&apo ...

I encountered an error of "Unexpected token '>'" while working with an

My code includes an ajax call and utilizes promises in the function: element.on("keypress", ".keyEvents", function(event) { if (event.which == 13) { // create the url and json object var putUrl = ...

js issue with passing form data to use with PHP mail function

As a novice, I am diving into the world of HTML webpage creation. Utilizing a free online template, my current project involves developing a Contact Page that triggers a php script to send an email with the captured fields. While I've successfully man ...

Using TypeScript to filter and compare two arrays based on a specific condition

Can someone help me with filtering certain attributes using another array? If a condition is met, I would like to return other attributes. Here's an example: Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}] Array2 = [{id ...