Search code examples
javascriptc#asp.net-coresweetalert2

Sweet Alert function doesn't trigger when it's called by a js script


I've been trying to make a simple validation if a user isn't logged in, trying to trigger a sweet alert message when this happens. This validation works if a customer is trying to add a new product to his shopping cart, but isn't logged in.

Note: the Session Variable is the actual Session known in asp.net core and the session variable is just an attribute of my viewmodel that contains this Session Variable.

I'm working with asp.net core 2.2, using Session variable which contains a User class obtained by serialization with Json, at first I've tried to call the session attribute of my view model in my view, but with no success, from what I've read I have to inject a IHttpContextAccessor in the view, in order to obtain the Session Variable and use it, but because I'm using serialization with Json I couldn't reach the GetObjectFromJson method in the view, so I gave up and tried to use ViewData["Session"] in order to pass the id of the User class to it, amd setting it to 0 if the Session Variable is null. This one worked and I managed to check that the session variable in the view, more specific in the js function it was 0, but anyways the Sweet Allert messaged didn't triggered.


// THIS IS MY ACTION METHOD IN THE CONTROLLER

        [Route("filtrar")]
        [HttpGet]
        public ActionResult Filter(String search)
        {
            HomeFilterViewModel homeFilterViewModel = new HomeFilterViewModel
            {
                tiposDeMaterialDiscografico = _tipoMaterialDiscografico.GetAll(),
                generos = _genero.GetAll(),
                sesion = HttpContext.Session.GetObjectFromJson<Usuario>("Usuario"),

                materialDiscograficos = _materialDiscografico.Search(search).Union(_materialDiscografico.PorArtista(search)).OrderBy(m => m.Nombre)
            };

            if (homeFilterViewModel.sesion != null && homeFilterViewModel.sesion.TipoUsuario.IdTipoUsuario == 2)
            {
                return RedirectToAction("Dashboard", "Admin");
            }

            return View(homeFilterViewModel);
        }

<!-- THIS IS MY VIEW WITH THE JS REFERENCES AND FUNCTIONS AT THE END -->

@model HomeFilterViewModel

@{
    ViewBag.Title = "Material Discográfico";
}

@section Filter {
    <link href="~/css/Filter.css" rel="stylesheet" />
}

<div class="container" style="margin-top: 22px;">
    <div class="row">
        @foreach (var material in Model.materialDiscograficos)
        {
            <div class="col-4" style="min-width: 100px; max-width: 35%">
                <div class="card img-responsive" id="thumb" data-toggle="modal" data-target="#@material.Nombre.Replace(" ", "")">
                    <button class="btn btn-light">
                        @if (material.ImagenPortada == null)
                        {
                            <img class="img-fluid" src="~/images/portadas/default.png" asp-append-version="true" style="padding: 13px;">
                        }
                        else
                        {
                            <img class="img-fluid" src="~/images/portadas/@material.ImagenPortada" asp-append-version="true" style="padding: 13px;">
                        }
                    </button>
                </div>
            </div>

            <div class="modal fade" id="@material.Nombre.Replace(" ", "")" role="dialog">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header text-center">
                            <h4 class="modal-title w-100">@material.Nombre</h4>
                        </div>
                        <div class="modal-body">
                            <h5><strong>Detalles:</strong></h5>
                            <br />
                            <div class="row">
                                <div class="col-lg-5">
                                    <p class="text-center">Autor: @material.Autor.NombreAutor</p>
                                    <p class="text-center">Género: @material.Genero.DescripcionGenero</p>
                                    <p class="text-center">Tipo: @material.TipoMaterialDiscografico.DescripcionTipoMaterialDiscografico</p>
                                    <p class="text-center">Duración Total (segundos): @material.DuracionTotalSegundos</p>
                                    <p class="text-center">Precio: @material.Precio</p>
                                    <p class="text-center">Stock: @material.Stock</p>
                                </div>
                                <br />
                                <div class="col-lg-5 col-centered" style="min-width: 100px; max-width: 35%">
                                    <div class="card img-responsive" id="thumb">
                                        @if (material.ImagenPortada == null)
                                        {
                                            <img class="img-fluid" src="~/images/portadas/default.png" asp-append-version="true" style="padding: 13px;">
                                        }
                                        else
                                        {
                                            <img class="img-fluid" src="~/images/portadas/@material.ImagenPortada" asp-append-version="true" style="padding: 13px;">
                                        }
                                    </div>
                                </div>
                            </div>
                            <h5><strong>Canciones:</strong></h5>
                            <br />
                            <div style="margin: 0 5% 0 5%">
                                @{
                                    if (material.Canciones != null)
                                    {
                                        <div class="row">
                                            <div class="col box"><br /><p class="text-center"><strong>Nombre</strong></p></div>
                                            <div class="col box"><br /><p class="text-center"><strong>Duración (segundos)</strong></p></div>
                                        </div>

                                        @foreach (var cancion in material.Canciones)
                                        {
                                            <div class="row">
                                                <div class="col box">
                                                    <br /><p class="text-center">@cancion.NombreCancion</p>
                                                </div>
                                                <div class="col box">
                                                    <br /><p class="text-center">@cancion.DuracionSegundos</p>
                                                </div>
                                            </div>
                                        }
                                    }
                                }
                            </div>
                            <br />
                        </div>
                        <form asp-controller="Cliente" asp-action="AgregarAlCarrito" method="get">
                            <div class="modal-footer">

                                <div style="float: left;"><button type="button" class="btn btn-outline-danger" data-dismiss="modal">Cerrar</button></div>
                                <div style="float: none;">
                                    <label>Cantidad:</label>
                                    <input type="number" name="cantidad" min="1" max="@material.Stock" />
                                    <input hidden type="text" name="idMaterial" value="@material.IdMaterialDiscografico" />
                                </div>
                                <div style="float: right;"><input type="submit" class="btn btn-outline-success" onclick="validateData();" value="Agregar al carrito" /></div>

                            </div>
                        </form>
                    </div>
                </div>
            </div>


        }

    </div>
</div>

@section SweetAlert2 {
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>
    <script src="sweetalert2/dist/sweetalert2.all.min.js"></script>
    <!-- Include a polyfill for ES6 Promises (optional) for IE11 -->
    <script src="https://cdn.jsdelivr.net/npm/promise-polyfill@8/dist/polyfill.js"></script>

    <script type="text/javascript">
    function validateData() {

        let sesion = @ViewData["Sesion"];

            if (sesion == 0) {
                Swal.fire({
                    type: 'error',
                    title: 'Oops...',
                    text: '¡Usted no ha iniciado sesión!',
                    footer: '<a asp-controller="Home" asp-action="Login">Iniciar sesión</a>'
                })

            }
    </script>
}


// THIS IS THE ACTION METHOD THAT THE FORM REDIRECTS TO

[HttpGet]
        public ActionResult AgregarAlCarrito(int idMaterial, int cantidad)
        {

            Usuario usuario = HttpContext.Session.GetObjectFromJson<Usuario>("Usuario");

            if(usuario == null || usuario.IdUsuario == 4 || usuario.IdUsuario == 1)
            {
                return RedirectToAction("Index", "Home");
            }

            CarritoCompras carrito = _carritoCompras.Get(usuario.CarritoCompras.IdCarritoCompras);
            MaterialDiscografico material = _materialDiscografico.Get(idMaterial);

            LineaDeVenta lineaDeVenta = new LineaDeVenta
            {
                Cantidad = cantidad,
                MaterialDiscografico = material,
                CarritoCompras = carrito
            };

            lineaDeVenta.TotalLinea = _lineaDeVenta.CalcularTotalLinea(lineaDeVenta.Cantidad, lineaDeVenta.MaterialDiscografico.Precio);
            lineaDeVenta.CarritoCompras.LineasDeVenta.Add(lineaDeVenta);
            _carritoCompras.Update(carrito);

            return RedirectToAction("ShoppingCart");
        }



// THIS IS MY VIEWMODEL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Entities;

namespace UI.ViewModels
{
    public class HomeFilterViewModel : ViewModelBase
    {
        public IEnumerable<MaterialDiscografico> materialDiscograficos { get; set; }
    }
}

I don't get any error messages it just doesn't trigger the Sweet Alert Message, I readed the documentation on how to add the Sweet Alert library and I'm not sure if I added it correctly or if my javascript function is working propperly.


Solution

  • You could always press F12 to open the DevTools and check the console tab in your browser whether there exists an error.And you will find that you miss a } in the end of js code.

    function validateData() {
    
        let sesion = @ViewData["Session"];
    
        if (sesion == 0) {
            Swal.fire({
                type: 'error',
                title: 'Oops...',
                text: '¡Usted no ha iniciado sesión!',
                footer: '<a asp-controller="Home" asp-action="Login">Iniciar sesión</a>'
            })
    
        }
    }