Giter VIP home page Giter VIP logo

razor.sweetalert2's Introduction

CurrieTechnologies.Razor.SweetAlert2

Blazor
โž•
SweetAlert2
A beautiful, responsive, customizable, accessible (WAI-ARIA) replacement for JavaScript's popup boxes.
All wrapped inside a Razor Component Library for use in Blazor Server and WebAssembly applications.
SweetAlert2 in action
See SweetAlert2 in action โ†—
Master Develop Version Downloads Mergify
Build Status Build Status Nuget Nuget mergify-status

๐Ÿ‘‰ Upgrading from v3.x to v4.x? Read the release notes!

๐Ÿ‘‰ Upgrading from v4.x to v5.x? Read the release notes!

This package is for both Blazor Server Apps and Blazor WebAssembly Apps. It should be used instead of CurrieTechnologies.Blazor.SweetAlert2 which is now deprecated.

๐Ÿ™Œ Includes themes from the Official SweetAlert2 Themes project ๐Ÿ™Œ

Installation

Install-Package CurrieTechnologies.Razor.SweetAlert2

Or install from the NuGet Package Manager

Usage

Register the service in your Startup file.

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
 services.AddSweetAlert2();
...
}

NB: For newer .NET 6 minimal project templates, this will actually be in Program.cs

// Program.cs
...
builder.Services.AddSweetAlert2();

OR

If you want to use one of the Official SweetAlert2 themes:

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
 services.AddSweetAlert2(options => {
   options.Theme = SweetAlertTheme.Dark;
 });
...
}

See Configuration for more information.

Add the script tag

Add this script tag in your root html file (Likely _Host.cshtml for Blazor Server or index.html for Blazor WebAssembly), right under the framework script tag. (i.e <script src="_framework/blazor.server.js"></script> for Blazor Server or <script src="_framework/blazor.webassembly.js"></script> for Blazor WebAssembly)

NB: In newer templates, this will be towards the bottom of Pages/_Layout.cshtml for Blazor Server or wwwroot/index.html for Blazor WebAssembly.

<script src="_content/CurrieTechnologies.Razor.SweetAlert2/sweetAlert2.min.js"></script>

If you need to support IE11, this script tag is different. See IE Compatibility.

_Imports.razor

Recommended: Add @using CurrieTechnologies.Razor.SweetAlert2 to your _Imports.razor file, to avoid having to put the using call in every component that requires it.

Inject the SweetAlertService into any Blazor component.

// Sample.razor
@inject SweetAlertService Swal;
<button class="btn btn-primary"
   @onclick="@(async () => await Swal.FireAsync("Any fool can use a computer"))">
 Try me!
</button>

Examples

The most basic message:

await Swal.FireAsync("Hello world!");

A message signaling an error:

await Swal.FireAsync("Oops...", "Something went wrong!", "error");

Handling the result of SweetAlert2 modal:

// async/await
SweetAlertResult result = await Swal.FireAsync(new SweetAlertOptions
 {
   Title = "Are you sure?",
   Text = "You will not be able to recover this imaginary file!",
   Icon = SweetAlertIcon.Warning,
   ShowCancelButton = true,
   ConfirmButtonText = "Yes, delete it!",
   CancelButtonText = "No, keep it"
 });

if (!string.IsNullOrEmpty(result.Value))
{
 await Swal.FireAsync(
   "Deleted",
   "Your imaginary file has been deleted.",
   SweetAlertIcon.Success
   );
}
else if (result.Dismiss == DismissReason.Cancel)
{
 await Swal.FireAsync(
   "Cancelled",
   "Your imaginary file is safe :)",
   SweetAlertIcon.Error
   );
}

// Promise/Task based
Swal.FireAsync(new SweetAlertOptions
 {
   Title = "Are you sure?",
   Text = "You will not be able to recover this imaginary file!",
   Icon = SweetAlertIcon.Warning,
   ShowCancelButton = true,
   ConfirmButtonText = "Yes, delete it!",
   CancelButtonText = "No, keep it"
 }).ContinueWith(swalTask =>
 {
   SweetAlertResult result = swalTask.Result;
   if (!string.IsNullOrEmpty(result.Value))
   {
     Swal.FireAsync(
       "Deleted",
       "Your imaginary file has been deleted.",
       SweetAlertIcon.Success
       );
   }
   else if (result.Dismiss == DismissReason.Cancel)
   {
     Swal.FireAsync(
       "Cancelled",
       "Your imaginary file is safe :)",
       SweetAlertIcon.Error
       );
   }
 });

Configuration

In Startup.cs you have the opportunity to configure how sweetalert2 will behave in your application.

Theme

With SweetAlertServiceOptions.Theme you can specify one of the official sweetalert2 themes to apply to your modal throughout your application.

SetThemeForColorSchemePreference()

With the SweetAlertServiceOptions.SetThemeForColorSchemePreference() method, you can specify which theme the user uses, based on the result of their prefers-color-scheme CSS media query. Most commonly this can be used to help create a dark version of your application, based on user preference. Browsers that do not support the prefers-color-scheme media query will fall back to the theme specified in SweetAlertServiceOptions.Theme

Theme Examples

If you want the default theme by default, and the dark theme if the user prefers a dark color scheme:

services.AddSweetAlert2(options => {
 options.SetThemeForColorSchemePreference(ColorScheme.Dark, SweetAlertTheme.Dark);
});

A dark theme by default, and a lighter theme if the user prefers a light color scheme:

services.AddSweetAlert2(options => {
 options.Theme = SweetAlertTheme.Dark;
 options.SetThemeForColorSchemePreference(ColorScheme.Light, SweetAlertTheme.Bootstrap4);
});

A minimal theme as a fallback, and a dark/light theme to match user preference:

services.AddSweetAlert2(options => {
 options.Theme = SweetAlertTheme.Minimal;
 options.SetThemeForColorSchemePreference(ColorScheme.Light, SweetAlertTheme.Default);
 options.SetThemeForColorSchemePreference(ColorScheme.Dark, SweetAlertTheme.Dark);
});

See prefers-color-scheme for more information.

Default Settings

If you want some settings globally applied to all of your SweetAlert2 dialogs, configure your default settings in Startup.cs

services.AddSweetAlert2(options => {
 options.DefaultOptions = new SweetAlertOptions {
   HeightAuto = false
 };
});

These can be overriden in individual FireAsync() calls.

NB: This will only apply to FireAsync() calls that take a SweetAlertOptions object as a parameter. The methods that take in primitive types bypass SweetAlertOptions entirely on both the C# and JS libraries.

Notable differences from the JavaScript library

  • No methods that return an HTMLElement are included (e. g. Swal.getHtmlContainer())
  • The value of a SweetAlertResult (result.Value) can only be a string. Numbers and booleans must be converted. Object must be parsed to/from JSON in your code.
  • DidOpenAsync(), WillCloseAsync(), WillOpenAsync(), and DidCloseAsync() can all take asynchronous callbacks. ๐ŸŽ‰ (none will return an HTMLElement though.)
  • No support for <optgroup> in the select input type.
  • No async option for InputOptions or InputValue
  • Callbacks must be passed inside of objects specifically designed for the given callback property. e.g. the InputValidator property takes an InputValidatorCallback created like so:
new SweetAlertOptions {
 ...
 InputValidator = new InputValidatorCallback((string input) => input.Length == 0 ? "Please provide a value" : null, this),
 ...
}

this is passed in so that the Blazor EventCallback used behind the scenes can trigger a re-render if the state of the calling component was changed in the callback. If the callback does not require the calling component to re-render, passing in this is optional. These callbacks are necessary because there is currently no way to create an EventCallback in Blazor that isn't a component parameter without using the EventCallbackFactory which is clunky. It also allows the callback to return a value that can be used by the SweetAlert2 library. (e.g. A validation message to show if input validation fails.) Native Blazor EventCallbacks only return generic Tasks.

Browser compatibility

IE11* Edge Chrome Firefox Safari Opera UC Browser
โŒ โœ” โœ” โœ” โœ” โœ” โœ”

IE Compatibility*

IE Compatibility has been removed in v5 due to sweetalert2@11 dropping their support for it.

If you need to support IE11, use v4 or earlier, and use this script tag instead. (file size is about 35% larger)

<script src="_content/CurrieTechnologies.Razor.SweetAlert2/sweetAlert2.ieCompat.min.js"></script>

You will also likely need to utilize the Blazor.Polyfill library, for general Blazor functionality in IE.

Protestware

Currently, the original sweetalert2 library contains protestware to disable Russian websites using sweetalert2 when visited by Russian-speaking users. This wrapper library bypasses the effects of that protestware, so there should be no undesired effects when using this library.

Related projects

razor.sweetalert2's People

Contributors

alislin avatar basaingeal avatar dependabot-preview[bot] avatar dependabot[bot] avatar greenkeeper[bot] avatar mergify[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

razor.sweetalert2's Issues

'IServiceCollection' does not contain a definition for 'AddSweetAlert2'

After Installing the nuget package, tried adding "services.AddSweetAlert2();" to Startup.cs. Getting this error message

Error CS1061 'IServiceCollection' does not contain a definition for 'AddSweetAlert2' and no accessible extension method 'AddSweetAlert2' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?) Test C:....\Startup.cs 31 N/A

Width Option not working

Describe the bug
The Width Option in SweetAlertOptions is not working. Changing the value does not have any effect on the Alert.

To Reproduce

await Swal.FireAsync(new SweetAlertOptions
{
    Title = "Some Message",
     Width = "500",
     Background = "#fff url(someimage)"
});

Expected behavior
The Alert should change in Width size. I even tried dumb number, like 10, 1000, and such. They had no different effect.

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser: Firefox (does work with SweetAlert2 in JS though, tested it on this browser)

Edit:
Changed code snippet to code tag

Dev Dependencies

Hello, I'm trying to contribute, but I'm not sure how to get this to build properly. Webpack doesn't like the dependencies. Is there anything special i need to get this to build and output the javascript/typescript/css properly? .Net library builds fine.

Action required: Greenkeeper could not be activated ๐Ÿšจ

๐Ÿšจ You need to enable Continuous Integration on Greenkeeper branches of this repository. ๐Ÿšจ

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didnโ€™t receive a CI status on the greenkeeper/initial branch, itโ€™s possible that you donโ€™t have CI set up yet.
We recommend using:

If you have already set up a CI for this repository, you might need to check how itโ€™s configured. Make sure it is set to run on all new branches. If you donโ€™t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, youโ€™ll need to re-trigger Greenkeeperโ€™s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

Blazor web app in NET Core 8

The Sweetalert2 v5.5.0 works fine in Blazor Server app in NET Core 8. But In Blazor web app in NET Core 8 the error is
Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.
at sweetAlert2.min.js:1:69148
at sweetAlert2.min.js:1:69186
at sweetAlert2.min.js:1:70882
at sweetAlert2.min.js:1:70886
Are there any plans to support the Blazor web app in NET Core 8?

Example is incorrect

Hi,

@onclick="(async () => await Swal.FireAsync("Any fool can use a computer"))">
should be
@onclick="@(async () => await Swal.FireAsync("Any fool can use a computer"))">

Being a Blazor new comer, it took me a while to figure out why it didn't work

Target property in SweetAlertOptions doesn't appear to be working

Describe the bug

When using the Target property of SweetAlertOptions, the resulting alert isn't coming from the given target as expected.

To Reproduce

@inject SweetAlertService Swal
...
await Swal.FireAsync(new SweetAlertOptions
{
    Target = ".main",
    Icon = SweetAlertIcon.Error,
    Title = "Title",
    Html = "Message",
    ConfirmButtonText = "Ok",
});

Expected behavior
The alert should "come from" the target element. (be centered in etc.)

Themes sometimes don't work

Theming currently only works when the Swal service is injected after page load. So if the load page does not have a component that injects SweetAlertService and then a component that does is loaded, it will work. But if the loaded page has a Swal component, it will not work.

This is because currently, setting the theme is done dynamically via JSInterop in the SweetAlertService constructor. This works well if there's already a page to manipulate, but before the fact it doesn't.

Need to somehow run the process after page load, or re-work all together.

If nothing works, a manual link tag may be needed, and the relevant documentation will be provided.

Action required: Greenkeeper could not be activated ๐Ÿšจ

๐Ÿšจ You need to enable Continuous Integration on Greenkeeper branches of this repository. ๐Ÿšจ

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didnโ€™t receive a CI status on the greenkeeper/initial branch, itโ€™s possible that you donโ€™t have CI set up yet.
We recommend using:

If you have already set up a CI for this repository, you might need to check how itโ€™s configured. Make sure it is set to run on all new branches. If you donโ€™t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, youโ€™ll need to re-trigger Greenkeeperโ€™s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

Bug Color - Razor/Blazor

SweetAlertResult result = await _swal.FireAsync(new SweetAlertOptions
{
TitleText= title,
Text = message,
Color = "Black",
Background = "#FBF9F9",
Icon = SweetAlertIcon.Warning,
IconColor = "Red",
ButtonsStyling = true,
ShowCancelButton = false,
ConfirmButtonColor = "Black",
ConfirmButtonText = textButtonOK,
HeightAuto = false
}); ; ;

		return result;

https://prnt.sc/yhIyEWOx1rwW

not respect color Color = "Black", to text

CustomClass adds to buttons but does not replace

Having this code:

var result = await Swal.FireAsync(
    new SweetAlertOptions
    {
        Title = "Really delete ticket?",
        Text = "Do you really want to permanently delete the ticket?",
        Icon = SweetAlertIcon.Question,
        ShowCancelButton = true,
        FocusCancel = true,
        ConfirmButtonText = "Delete ticket",
        CancelButtonText = "Cancel",
        CustomClass = new SweetAlertCustomClass
        {
            ConfirmButton = @"btn btn-outline-primary",
            CancelButton = @"btn btn-outline-secondary"
        }
    });

I'm trying to apply Bootstrap styles btn btn-outline-primary and btn btn-outline-secondary to the SweetAlert2 buttons.

In my normal Blazor forms, these buttons look like this:

image

In a SweetAlert2 dialog, they look like this, though:

image

I.e. they look the same as without using the CustomClass property.

Having a deeper look at the generated HTML in Chrome's F12 tools, the generated markup looks like this:

<button 
    type="button" 
    class="swal2-confirm btn btn-outline-primary swal2-styled" 
    aria-label="" 
    style="display: inline-block; border-left-color: rgb(48, 133, 214); border-right-color: rgb(48, 133, 214);">
    Delete ticket
</button>

I.e. not only is my own class definition set to the class attribute of the <button> but in addition, the existing classes swal2-confirm, swal2-styled are still present, and also a style attribute is set with inline CSS.

I'm using a dark Windows theme, so the @media (prefers-color-scheme: dark) should somewhere kick in.

My expected behaviour is that only the classes I explicitely set are present in the buttons, no other classes, no inline CSS.

There is an example on the original SweetAlert2 website (Search for "bootstrap" on the page to find it).

I'm using your latest library on a German Windows 10 64 Bit with dark colors and Google Chrome version 81.0.4000.3 (official build) dev (64-Bit).

swal2-input conficts with open Bootstrap 4 modal

Describe the bug
When I fire SweetAlert2 with input, the input is disabled and I cannot type in it

To Reproduce
Method triggered on load and button onclick

private async Task ConfirmRemoveItemAsync(MarketItem marketItem)
{
    await Swal.FireAsync(new SweetAlertOptions()
    {
        Title = "Are you sure?",
        Text = $"{marketItem.Id} ({marketItem.ItemName}) will be moved to your buyings",
        Icon = SweetAlertIcon.Warning,
        ShowCancelButton = true,
        ConfirmButtonText = "Yes, remove it!"
    }).ContinueWith(async (swalTask) => 
    {
        if (Convert.ToBoolean(swalTask.Result.Value))
        {
            await RemoveItemAsync(marketItem);
        }
    });
}

Expected behavior
I should be able to write in input even if Bootstrap modal is opened

Screenshots
OnInitialized when Bootstrap modal isn't opened
image

When triggered by "Change Price" button when Bootstrap modal is opened
image

Question: PreconfirmCallback cant perform http request?

Describe the bug
I would like to make http delete request withing preconfirm callback. However my call never make it to server and value is returned.

To Reproduce

SweetAlertResult result = await SweetAlert.FireAsync(new SweetAlertOptions
{
    Icon = SweetAlertIcon.Warning,
    ShowCancelButton = true,
    PreConfirm = new PreConfirmCallback(async() =>
    {
        try
        {
            await Http.DeleteAsync($"api/Product/{item.Id}");

            return "1";
        }
        catch
        {
            return "0";
        }
    })
});

Expected behavior
Wait till http delete make request then return "1".

Provide a config option to remove the use of "swal2-height-auto" in Swal2's CSS

When Swal2 pops open it's dialog, it places 2 class names on the document body, one of which is the "swal2-height-auto" class.

In some layouts, this is undesirable, as it breaks the layout. By way of an example, I'm currently working on an app that has a fixed height, with inner scrolling area layout. It looks like this:

image

When I open a Swal2 dialog however

image

The footer bar is moved to the bottom of the content instead of remaining at the bottom of the screen where the green arrow is pointing.

As can be seen in the web-dev tools:

image

the height auto class is applied.

If I use the dev-tools to remove the class

image

The footer returns to the bottom, but the swal display still remains ok.

image

Being able to control this classes use in the options for Swal2 would be advantageous.

How to add custom inputs?

Describe the bug
There are only a handful of examples, and these only show simple dialogs without custom input.

To Reproduce
How do you set options to add custom inputs?

Expected behavior

Screenshots

Desktop (please complete the following information):

Smartphone (please complete the following information):

Additional context

Setup for WebAssembly

Describe the bug
I tried following the documentation for setup with Blazor using WebAssembly but I'm unable to successfully get it working.

To Reproduce
Steps to reproduce the behavior: (tried to follow readme documentation)

  1. Install CurrieTechnologies.Razor.SweetAlert2 version 3.0.0
  2. Add builder.Services.AddSweetAlert2(); to Main() in Program.cs
  3. Add <script src="_content/CurrieTechnologies.Razor.SweetAlert2/sweetAlert2.min.js"></script> to index.html
  4. Add @using CurrieTechnologies.Razor.SweetAlert2 to _Imports.razor
  5. Add @inject SweetAlertService Swal; to FooPage.razor
  6. Add <button class="btn btn-primary" @onclick="(async () => await Swal.FireAsync("Any fool can use a computer"))">Try me!</button> to FooPage.razor

Expected behavior
FooPage.razor compiles and runs

Actual behavior
FooPage.razor reports error: CS1026 ) expected

Additional context
Running Visual Studio 2019 16.8.0 Preview 3.1 with net5.0 (rc1)

[Documentation]

You show using the component in mvc but you dont show how to use it in a controller yes you show the code.
But how do i register it on the controller side as when i use the below code it doesnt reconise swal.
Swal.FireAsync(
"Cancelled",
"Your imaginary file is safe :)",
SweetAlertIcon.Error
);

razorpage .net6

1- i installed package.
2-add builder.services. and in index page add using CurrieTechnologies.Razor.SweetAlert2;
3- how can I use basically show message.

public void OnPostSave()
{
Swal.FireAsync("Hello world!");
}
Swal does not exist in the current context. :(

Interface IAsyncSweetAlertService: public instead of protected

Is your feature request related to a problem? Please describe.
Both public classes SweetAlertService and SweetAlertMixin implement the protected interface IAsyncSweetAlertService. For unit testing our razor component we use bUnit. A convinient possibility for simulate the confirming oder denying the SweetAlert popup could be using Moq. But mocking a protected or private interface is not supported.

Describe the solution you'd like
Change the access modifier of the interface IAsyncSweetAlertService to public, if there is no special reason for the interface to be protected.

Missing Stylesheet after navigating in .NET 8

Issue

After navigating away and back to a page, a call to Swal.FireAsync() shows an alert that has CSS missing.

Steps

I've created a new Blazor Web App with these configuration settings:

image

I then added

<PackageReference Include="CurrieTechnologies.Razor.SweetAlert2" Version="5.5.0" />

to my project's CSPROJ file, added

<script src="_content/CurrieTechnologies.Razor.SweetAlert2/sweetAlert2.min.js"></script>

right to the end before the </body> tag:

image

and added this to my "Program.cs":

builder.Services.AddSweetAlert2(options =>
{
	options.Theme = SweetAlertTheme.Dark;
	options.SetThemeForColorSchemePreference(ColorScheme.Light, SweetAlertTheme.Default);
	options.SetThemeForColorSchemePreference(ColorScheme.Dark, SweetAlertTheme.Dark);
});

Next, I created a simple button in "Home.razor":

<button @onclick="@(async ()=>await Swal.FireAsync("Test!"))">Test, klick!</button>

I've also changed @rendermode InteractiveServer on that page. The full source code of the page looks like this:

@page "/"
@rendermode InteractiveServer
@inject SweetAlertService Swal

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<button @onclick="@(async ()=>await Swal.FireAsync("Test!"))">Test, klick!</button>

This results in this:

image

When I click the button, it shows this alert:

image

I can do this multiple times successfully.

Next, I navigate to another page:

image

And then I navigate back to the home page:

image

When I then click the button, the alert appears, but it seems to have no styling:

image

It is shown that the bottom left of the page.

It seems to work correctly (i.e. I can click the OK button to close the alert), but it looks wrong.

Expected behavior

I would expect that Razor.SweetAlert2 works every time, not just when I do not navigate.

Desktop

  • OS: Windows 11 German, 64 bit
  • Browser: Google Chrome Version 120.0.6099.71 (Offizieller Build) (64-Bit)

Can you please provide documentation on how to implement Ajax with the PreConfirm Callback?

Awesome Blazor wrapper for the SweetAlert library.

I'd like to use the Ajax feature but the code below (sweetAlert2 Ajax Sample) doesn't work.

 async Task ShowGithubAvatar()
    {
        try
        {
            var result = await Swal.FireAsync(new SweetAlertOptions
            {
                Title = "Submit your Github username",
                Input = SweetAlertInputType.Text,
                InputAttributes = new Dictionary<string, string> { { "autoCapitalize", "off" } },
                ShowCancelButton = true,
                ConfirmButtonText = "Look Up",
                ShowLoaderOnConfirm = true,
                PreConfirm = new PreConfirmCallback(async (username) => {
                    var response = await Http.GetAsync($"https://api.github.com/users/{username}");
                    response.EnsureSuccessStatusCode();
                    return await response.Content.ReadAsStringAsync();
                }, this),
                AllowOutsideClick = await Swal.IsLoadingAsync()
            });

            if (!string.IsNullOrEmpty(result.Value))
            {
                dynamic githubProfile = JToken.Parse(result.Value);

                await Swal.FireAsync(new SweetAlertOptions
                {
                    Title = $"{githubProfile.login}'s avatar",
                    ImageUrl = githubProfile.avatar_url
                });
            }
        }
        catch (Exception ex)
        {
            await Swal.ShowValidationMessageAsync($"Request failed: {ex.Message}");
        }
    }

Can you please provide some clarification around this?

Is there a similar library for .NET Core MVC?

Using your library successfully for over a year now in a server-side Blazor project.

Now I'm looking for a similar library that allows me to use Sweetalert2 in a more comfortable way in my ASP.NET Core MVC projects, too.

Ideally the same C# syntax that I use your library today in my Blazor apps.

I found NToastNotify that does a great job of providing an abstraction layer to Noty and Toastr, but unfortunately I found no library that does the same for Sweetalert2.

Is anyone aware of such a library?

Flickering problem

When swal.Fire() is called, the sweetalert dialog is shown for milliseconds in the center of the screen and then it's animated fading from up to down causing a little flick. Is there any way to avoid this?

CI/CD

Right now the publish process is a follows:

  • Make changes for next version.
  • Build TypeScript front-end
  • Update Nuget package changelog
  • Commit
  • Create Github release
    • Re-write changelog
    • Attach Nuget package to release
  • Upload Nuget package to Nuget

I'd like to automate almost all of that. That will involve a few things.

  • Get off of master. Switch to GitFlow.
  • Empty the wwwroot folder. No longer commit any build files.
  • Run CI on Azure DevOps for both master and dev branches.
  • The CI will build the TypeScript and pack the nuget package.
  • If possible, commits to master will trigger a Github release.
  • Either the commit to master or the Github release will trigger a Nuget package update.

It may turn out that I only publish the package to an Azure DevOps feed and then manually update on Nuget.org so that new versions aren't pushed by accident.

5.1.0 Throwing JSDisconnectedException after browser closed, left then reopened

Tried this with .net6.0 official release version and working very well generally however, if you display a SWAL dialog, then close your browser window with your web application still running and wait for approximately 2 minutes and try and use the same SWAL dialog a JSDisconnectedException is thrown when calling SWAl.FireAsync.

I am only using JS interop functionality in OnAfterRenderAsync as recommended by MS

Microsoft.JSInterop.JSDisconnectedException
HResult=0x80131500
Message=JavaScript interop calls cannot be issued at this time. This is because the circuit has disconnected and is being disposed.
Source=Microsoft.AspNetCore.Components.Server
StackTrace:
at Microsoft.AspNetCore.Components.Server.Circuits.RemoteJSRuntime.BeginInvokeJS(Int64 asyncHandle, String identifier, String argsJson, JSCallResultType resultType, Int64 targetInstanceId)
at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, CancellationToken cancellationToken, Object[] args)
at Microsoft.JSInterop.JSRuntime.d__161.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Threading.Tasks.ValueTask1.get_Result()
at CurrieTechnologies.Razor.SweetAlert2.SweetAlertService.d__18.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at ----- .Application.Shared.NavMenu.<>c__DisplayClass27_0.<b__0>d.MoveNext() in ---
This exception was originally thrown at this call stack:
[External Code]

Expected behavior
The IJSRuntime is injected without issue

Fails with multiple browsers.

Visual Studio 2022 net6.0 both released official versions

Global setup options on the service registration

Is your feature request related to a problem? Please describe.
Yes, I need to setup globally HeightAuto = false since this breaks pages using flex and height 100%.

This is my case as specified in sweet alert 2

image

Describe the solution you'd like
Global options setup in the services.AddSweetAlert2();

Describe alternatives you've considered
What I have done for now is refactor the methods using FireAsync.

Used the overload method with the sweet alert options and force HeightAuto = false.

Additional context
N/A

It's seems to be possible using Swal.mixin({ ...options })

https://sweetalert2.github.io/#configuration

I searched the source code and there is no overload here

https://github.com/Basaingeal/Razor.SweetAlert2/blob/develop/ExtensionMethods.cs

Use Generics in SweetAlertResults

Right now the Value of a SweetAlertResult can only be a string.

Create Generic versions of Swal.FireAsync(), Swal.QueueAsync(), and SweetAlertResult so that users can specify the return type they expect.

'CurrieTechnologies' was undefined Error

I'm using blazor wasm, registered the sweet alert service in Program.cs, added the sweet alert script below the framework script as indicated and injected the SweetAlertService into a component but when trying to call FireAsync() I'm getting the following exception:

Microsoft.JSInterop.JSException: Could not find 'CurrieTechnologies.Razor.SweetAlert2.FireSettings' ('CurrieTechnologies' was undefined).
Error: Could not find 'CurrieTechnologies.Razor.SweetAlert2.FireSettings' ('CurrieTechnologies' was undefined).

I am also unable to inject SweetAlertService into a component without the @using CurrieTechnologies.Razor.SweetAlert2 directive.

'CurrieTechnologies' was undefined

I have integrated the library in blazor wasm net6 application, until some week ago it works well.

Now when i try to open an alert it raise this error on console:

image

index.html is not changed and contains reference to js ( <script src="_content/CurrieTechnologies.Razor.SweetAlert2/sweetAlert2.min.js"></script>)

any help?

Target .Net Standard

Deprecate Basaingeal/Blazor.SweetAlert2
The plan is to completely replace Basaingeal/Blazor.SweetAlert2 with this library. In order to do that, we'll need to target .Net Standard instead of .Net Core.

There is a problem in .Net 3.0-preview-6 where the static files referenced in a Razor class library are referenced differently in Server-side and Client-side Blazor. (dotnet/aspnetcore#11174) So this will have to wait until preview-7, which should be days away.

Support the "prefers-color-scheme" media query for themes

Introduction

There is a new media query prefers-color-scheme that allows a website to provide separate styles for both dark and light themes that recently is supported by most major browsers.

I'm using this for my websites heavily already with great success, especially now that iOS 13 is out that supports a dark theme, too.

Suggested Feature

My suggestion is to enhance your library to also support this, when it comes to specifying themes.

Details

Looking at this code from your readme to define a theme to use:

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
	services.AddSweetAlert2(options => {
		options.Theme = SweetAlertTheme.Dark;
	});
...
}

My suggestion is to enhance this in a way to be able to specify multiple themes.

I can think of something like this:

options.Theme = SweetAlertTheme.Default;
options.ThemeDark = SweetAlertTheme.Dark;

I.e. having multiple properties:

public class SweetAlertServiceOptions
{
    public SweetAlertTheme Theme { get; set; }
    public SweetAlertTheme ThemeLight { get; set; }
    public SweetAlertTheme ThemeDark { get; set; }
}

Or, as another example something like this:

options.SetTheme(ColorScheme.NoPreference, SweetAlertTheme.Default);
options.SetTheme(ColorScheme.Dark, SweetAlertTheme.Dark);

with these options.

public class SweetAlertServiceOptions
{
    public SweetAlertTheme Theme { get; set; } // Default.
    public SweetAlertTheme SetTheme(SweetAlertTheme theme); // Default, alternative.
    public SweetAlertTheme SetTheme(ColorScheme scheme, SweetAlertTheme theme);
}

The implementation could simply output all refered themes together with the media query, e.g.:

<link rel="stylesheet" id="currietechnologies-razor-sweetalert2-theme-link-1" href="_content/CurrieTechnologies.Razor.SweetAlert2/darkTheme.min.css" data-theme-number="1" media="(prefers-color-scheme: dark)">
<link rel="stylesheet" id="currietechnologies-razor-sweetalert2-theme-link-2" href="_content/CurrieTechnologies.Razor.SweetAlert2/minimalTheme.min.css" data-theme-number="2" media="(prefers-color-scheme: light)">
...

I.e. you simply iterate all set themes and output it together with the media query (if specified). This also works for browsers that do not support it if done like this.

remove newly deprecated feautres

This library as a rule does not include functionality for deprecated features. And features that were deprecated by v9.0 need to be removed.

Swal.IsLoadingAsync() is broken

Swal.IsLoading is not exposed as a method on the window object.

Swal IsLoadingAsync()

Possibly due to a typo in SweetAlert.ts

razorSwal.HideLoading = (): void => {
  Swal.hideLoading();
};

razorSwal.HideLoading = (): boolean => {
  return Swal.isLoading();
};

.Net 6 Support

Hi There! We Love your Sweet Alert 2 for Blazor Project! Its Very helpful and useful! Just wondering if the below nuget is compatible with .Net 6? if not, will it be by the time .Net 6 releases early November 2021?

image

FireAsync with SweetAlertOptions not working with custom JsRuntime serialization

Hi,

if i call Swal.FireAsync(title, message, icon) all work well

but if i use the SweetAlertOptions parameter it show an empty dialog and chrome dev tools give me below warnings.

var settings = new SweetAlertOptions
            {
                Text = message,
                Title = title,
                ConfirmButtonText = confirmButtonText,
                CancelButtonText = cancelButtonText,
                ShowCancelButton = true,
                Icon = SweetAlertIcon.Warning
            };

            var result = await Swal.FireAsync(settings);

image

the cause of this is the js runtime serialization settings who i have modified keeping the properties case as below:

public static IServiceProvider ConfigureJsRuntimeSerialization(this IServiceProvider services)
        {
            try
            {
                //https://github.com/dotnet/aspnetcore/issues/12685
                //Keep property case in serialization with jsRuntime.InvokeAsync
                var jsRuntime = services.GetService<IJSRuntime>();
                var prop = typeof(JSRuntime).GetProperty("JsonSerializerOptions", BindingFlags.NonPublic | BindingFlags.Instance);
                var value = (JsonSerializerOptions)Convert.ChangeType(prop.GetValue(jsRuntime, null), typeof(JsonSerializerOptions));
                value.PropertyNamingPolicy = null;
                value.DictionaryKeyPolicy = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ConfigureJsRuntimeSerialization Error: {ex.Message}");
            }

            return services;
        }

can sweetAlert2 keep compatibility with this settings?

i think it will require only to set the [JsonPropertyName("lowerCase")] in the SweetAlertOptionPOCO class properties

Thanks

`iconHtml`

Use any HTML inside icons (e.g. Font Awesome)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.