当由js脚本调用时,Sweet Alert函数不会触发

时间:2019-06-30 17:15:52

标签: javascript c# asp.net-core sweetalert2

如果用户未登录,我一直在尝试进行简单的验证,并尝试在发生这种情况时触发警告消息。如果客户尝试将新产品添加到购物车中但未登录,则此验证有效。

注意:会话变量是asp.net核心中已知的实际会话,而该会话变量只是我的包含该会话变量的视图模型的属性。

我正在使用asp.net core 2.2,使用Session变量,其中包含通过Json序列化获得的User类,起初我尝试在视图中调用视图模型的session属性,但没有成功,从我阅读的内容来看,我必须在视图中注入IHttpContextAccessor才能获取会话变量并使用它,但是由于我正在使用Json进行序列化,因此无法在视图中访问GetObjectFromJson方法,因此我放弃了尝试使用ViewData [“ Session”]来将User类的ID传递给它,如果Session Variable为null,则将其设置为0。这个工作正常,我设法检查视图中的会话变量,在js函数中更具体地是0,但是无论如何都没有触发Sweet Allert消息。


// 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; }
    }
}

我没有收到任何错误消息,只是没有触发Sweet Alert消息,我阅读了有关如何添加Sweet Alert库的文档,并且不确定是否正确添加了它或我的javascript函数工作正常。

1 个答案:

答案 0 :(得分:1)

您总是可以按F12键打开DevTools并在浏览器中检查控制台选项卡是否存在错误。然后您会发现您错过了js代码结尾的>

}