gpt4 book ai didi

javascript - Sweet Alert函数在js脚本调用时不会触发

转载 作者:行者123 更新时间:2023-12-02 23:23:51 26 4
gpt4 key购买 nike

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

注意: session 变量是 ASP.NET Core 中已知的实际 session , session 变量只是包含此 session 变量的 View 模型的一个属性。

我正在使用asp.net core 2.2,使用Session变量,其中包含通过Json序列化获得的User类,首先我尝试在我的 View 中调用我的 View 模型的session属性,但没有成功,根据我读到的内容,我必须在 View 中注入(inject) IHttpContextAccessor,以便获取 session 变量并使用它,但因为我使用 Json 进行序列化,所以无法访问 View 中的 GetObjectFromJson 方法,所以我放弃并尝试使用 ViewData["Session"] 来将 User 类的 id 传递给它,如果 session 变量为 null,则将其设置为 0。这个有效,我设法检查 View 中的 session 变量,更具体地说,在 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 函数是否正确工作正常。

最佳答案

您可以随时按F12打开DevTools,检查浏览器中的控制台选项卡是否存在错误。您会发现js代码末尾少了一个}

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>'
})

}
}

关于javascript - Sweet Alert函数在js脚本调用时不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56826663/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com