Prevent closure of Bootstrap offcanvas on backdrop click in a Blazor .NET application

Trying to implement an offcanvas window form and ensuring it stays open only when the user clicks the close button. Following client requirements, I need to call the offcanvas window via C# with IJSRuntime injection instead of directly from HTML.

Operating on .NET 8 using Blazor framework, below are the code snippets:

Razor file snippet:

<button class="btn btn-primary" type="button" data-bs-dismiss="offcanvas" data-bs-backdrop="static" @onclick="() => ShowCanvas()">Show Canvas</button>

C# method block:

async void ShowCanvas()
{
    await JS.InvokeVoidAsync("showOffCanvas");
}

Javascript function snippet:

function showOffCanvas() {
    var myCanvas = new bootstrap.Offcanvas(document.getElementById('offcanvasWindow'));
    myCanvas.show();
}

Encountered an exception during application run, details below:

Microsoft.JSInterop.JSException: 'OFFCANVAS: Option "backdrop" provided type "string" but expected type "boolean".
TypeError: OFFCANVAS: Option "backdrop" provided type "string" but expected type "boolean".  
(Additional error stack trace provided)

Any suggestions for resolving this issue using IJSRuntime method?

Thank you.

Tried omitting data-bs-dismiss="offcanvas" attribute and modified JS code as follows:

function showModalItemMasterForm() {
    var myCanvas = new bootstrap.Offcanvas(document.getElementById('offcanvasWindow'), 
    { backdrop: 'static', keyboard: false });
    myCanvas.show();
}

However, encountering the same error message.

Answer №1

If you want to interact with an OffCanvas without using JavaScript, here is a simple implementation that does not require any JS:

OffCanvas.razor

<div class="@_showCss" tabindex="-1">
    <div class="offcanvas-header">
        <h5 class="offcanvas-title">Offcanvas Header</h5>
        <button type="button" class="btn-close text-reset" @onclick="this.Hide"></button>
    </div>
    <div class="offcanvas-body">
        <p>
            Content for the offcanvas goes here. You can place just about any Bootstrap component or custom elements here.
        </p>
    </div>
</div>
@if (this.Show)
{
    <div class="modal-backdrop fade show"></div>
}

@code {
    [Parameter] public bool Show { get; set; }
    [Parameter] public EventCallback<bool> ShowChanged { get; set; }
    private string _showCss => this.Show ? "offcanvas offcanvas-start show off-canvas-show" : "offcanvas offcanvas-start  off-canvas-hide";
    private TaskCompletionSource? _taskCompletionSource;

    public void Hide()
    {
        this.ShowChanged.InvokeAsync(false);
    }
}

OffCanvas.razor.css

.off-canvas-show {
    visibility:visible;
    z-index:1100 !important;
}
.off-canvas-hide {
    visibility: hidden;
}

Check out the Home demo below:

@page "/"

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<div class="m-2">
    <btn class="btn btn-primary" @onclick="Open">Show OffCanvas</btn>
</div>

<OffCanvas @bind-Show="_showOffCanvas"/>

@code {
    private OffCanvas? _offCanvas;
    private bool _showOffCanvas;

    private void Open()
    {
        _showOffCanvas = true;
    }
}

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

Managing the uploading of files when a new property is included directly from the JavaScript File Object

When processing files using the POST method, I am able to access the default information such as name, type, size, tmp_name, and error through PHP. However, the file being sent contains additional data that I need PHP to extract. https://i.sstatic.net/bGj ...

Sequentially calling URLs in Selenium NodeJS to retrieve the page source of each

I am trying to open URLs based on the IDs available in an array and retrieve the unique PageSource for each. However, when I run the code below, only the PageSource of the last element is being returned. For example, if the body of each URL looks like: ...

Determine if a cookie is set in Vue.js without requiring a page refresh

My current goal with VUE is to make the login url disappear from the navigation bar as soon as the user logs in. After successfully logging in, the token cookie is set in the browser. However, the issue arises when the login url remains visible in the nav ...

Recalling the layout following the user's computer restart

I am creating a simple online editing tool (similar to Microsoft Outline) for coursework and I would like the outline details to be saved even if the user restarts the system. How can I achieve this? <html> <head> <title>Editor</ ...

Is there a way to separate a string using two different delimiters?

Here is my code snippet : <template> ... <p v-for="club in clubs">{{club}}</p> ... </template> <script> export default { data: () => ({ clubs: '' }), mounted () { let dataClub = "- ...

Populate the AngularJS scope with a dynamically generated array

My Angular Application is functioning properly with <script> var app = angular.module('MyApp', []); app.controller('myCtrl', function ($scope, $sce) { $scope.urls = [ { "url": $sce.t ...

I'm struggling to grasp the concept of State in React.js

Even though I'm trying my best, I am encountering an issue with obtaining JSON from an API. The following error is being thrown: TypeError: Cannot read property 'setState' of undefined(…) const Main = React.createClass({ getInitia ...

What is the best way to set the tab as "active" in the first iteration of a PHP while loop?

When using a while loop to populate tabs with PHP, maintaining only one active tab at a time can be tricky. I have grasped that assigning the 'active' class within the loop causes all tabs to become active. So, how should I modify the script if I ...

Addressing three visual problems with an html form input, dropdown menu, and clickable button

Currently, the output of my code looks like this: https://i.stack.imgur.com/pl5CJ.jpg The first box (squared) represents an <input>, while the second box (rectangled) is a <select>. There are several issues that I am facing: The text entered ...

Discover which npm module includes the lodash dependency

I've encountered a peculiar situation while using webpack to create a production bundle for my application. Even though I haven't explicitly installed `lodash` and it's not listed in my package.json file, I noticed that it's being added ...

Verify the presence of plain ASCII text

I need to verify if the file uploaded is in ascii plain text format. Can you suggest a method? $("#my_file").change(function(){ //alert if file is not ascii plain text }); <input type="file" name="my_file" id="my_file" /> ...

disappearing the link in a window.open popup

I have a situation where I am opening a window with the code window.open("mytest.aspx");. The issue arises when the user closes that pop-up window - I need to have the link on the parent page hidden. In essence, how can I hide the anchor link on the parent ...

Is there a way to showcase the data of each table row within the tr tag in an Angular 8 application?

I have been developing an application using Angular 8. The employee-list component is responsible for presenting data in a table format. Within the employee-list.component.ts file, I have defined: import { Component } from '@angular/core'; impo ...

AngularJS and CodeIgniter collaborating to bring server-side pagination

I am currently working on integrating pagination using AngularJS and CodeIgniter. The current implementation requires fetching all records at once. However, I aim to modify it so that the data can be retrieved one page at a time from the server during run ...

Drop and drag the spotlight

On my website, I am looking to implement a feature that will make it easier for users to identify the drag and drop area. I found a code snippet on JSFIDDLE that works perfectly there. However, when I tried to use it on my local server, it doesn't se ...

Implemented rounded corners to the bar chart background using Recharts

I have been experimenting with creating a customized bar chart that includes border radius for the bars. While I was successful in adding border radius to the bars themselves, I am struggling to add border radius to the background surrounding the bars. Any ...

Using Javascript in .NET to restrict the number of characters allowed in a textbox during typing and pasting

Consider this situation: I am attempting to display the indication "XY characters left" and restrict characters in a textbox as the user types. However, since I also have multiline textboxes, MaxLength doesn't always suffice (don't worry, I vali ...

Preventing Repeated Clicks in AngularJS

Looking for a better approach to handle double clicks in AngularJS other than using ng-disabled. I have a solution to disable double/multi-click functionality on button click and re-enable it after completing an ajax process. Any suggestions? When our cod ...

Implementing bind to invoke a function during an onClick Event

Here is a code snippet I have been working on that demonstrates how to handle click events on hyperlinks. The code features two hyperlinks named A and B. When hyperlink A is clicked, the console will log 'You selected A', and when B is clicked, ...

What is the best method for updating inner html with AJAX using the results obtained from json_encode?

If you need further clarification on how this works, feel free to check out this fiddle for a demonstration. In my setup, I have multiple DIVs each with a unique ID such as desk_85 (the number changes accordingly). <div class="desk_box_ver id="desk_8 ...