gpt4 book ai didi

javascript - 使用 foreach 循环 toast

转载 作者:行者123 更新时间:2023-12-03 05:20:14 25 4
gpt4 key购买 nike

我希望有人知道如何解决我的问题。因此,我安装了 Toastr 以在 ASP.NET MVC 应用程序中显示通知。我所拥有的是从 Controller 传递的每个元素的带有表和 foreach 循环的 View :

@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.CategoryName)
</td>
<td>
@Html.DisplayFor(modelItem => item.StartDate)
</td>
<td>
@{
Html.RenderAction("_CourseQuantityCount", "Course", new { item.CourseID });
}
/@Html.DisplayFor(modelItem => item.MaximumQuantity)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td id="alert">
@Html.ActionLink("SignIn", "SignIntoCourse", new { item.CourseID }, new { id = "myLink" })
</td>
</tr>
}
</table>

View 之后有一个脚本部分,如下所示:

@section scripts {  

<script type="text/javascript">
$(document).ready(function () {
toastr.options = {
"closeButton": false,
"debug": false,
"newestOnTop": false,
"progressBar": false,
"positionClass": "toast-top-center",
"preventDuplicates": false,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "5000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"

};
$('#alert').click(function () {
toastr.warning('Already signed!')
});
});

$('#myLink').click(function (e) {

e.preventDefault();
$.ajax({
url: $(this).attr("href"),
});

});
</script>
}

最后,如果我加载我的应用程序,它效果很好,但仅限于 foreach 循环中的第一个元素。目的是,如果用户登录类(class),他会收到一个他已经签名的 toast 。我认为问题可能出在所有 foreach 循环中的相同 id 上,但我不确定。而且我不知道如何创建多个id,然后以一种不刷新页面,只接收toast的方式在JS脚本中使用它。

最佳答案

您当前的代码正在生成具有多个具有相同 Id(myLink) 的 anchor 标记的标记。这不是有效的 HTML 标记。您的 ID 应该是唯一的。

您可以做的是,提供一个 css 类并将其用作 jQuery 选择器来连接单击事件。

<td>
@Html.ActionLink("SignIn", "SignIntoCourse", new { courseId= item.CourseID },
new { class = "myLink" })
</td>

现在监听具有css类的元素的点击事件

$(function(){

$("a.myLink").click(function(e){
e.preventDefault();
//do something here, may be make an ajax call.
});

});

现在您可以编写代码来对服务器方法进行 ajax 调用,该方法执行某些操作并返回响应。假设您的 SignIntoCourse 操作方法返回如下响应。

[HttpPost]
public ActionResult SignIntoCourse(int courseId)
{
//do your code to check and return either one of the response
if(alreadySignedUp) // your condition here
{
return Json(new { status="failed",message = "Already Signed into course" });
}
else
{
return Json(new { status="success",message = "Signed into course" });
}
}

现在,在 ajax 调用的成功回调中,您只需检查 json 数据的状态属性值并执行您必须执行的操作。

$(function(){

$("a.myLink").click(function(e){
e.preventDefault();
var url=$(this).attr("href");
$.post(url,function(data){
if(data.status==="success")
{
toastr.success(data.message, 'Success');
}
else
{
toastr.warning(data.message, 'Warning');
}
});
});

});

关于javascript - 使用 foreach 循环 toast ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41416902/

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