ASP中的Toast通知.NET MVC

Toast notifications in ASP.NET MVC

本文关键字:NET MVC 通知 Toast 中的 ASP      更新时间:2023-09-26

我在MVC应用程序中使用Toast通知插件来显示状态消息(成功编辑、更新、删除等),我想知道是否有一种简单的方法可以将一些逻辑放在Partial视图中,并将其放在我的Layout或每个需要的视图中。

部分

<script type="text/javascript">
    $(document).ready(function () {
        @if (ViewBag.Success == true) { 
            @:toastr.success("@ViewBag.Message");
        } else if (ViewBag.Success == false) {
            @:toastr.error("@ViewBag.Message");      
        }
    });
</script>

查看

//Doesn't work
@Html.Partial("_ToastPartial")
//Tried this directly in the view instead of using the partial, didn't work
@if (ViewBag.Success == true) { 
    @:toastr.success("@ViewBag.Message");
} else if (ViewBag.Success == false) {
    @:toastr.error("@ViewBag.Message");  
}

控制器

    public ActionResult SomethingAwesome(MyViewModel model)
    {
        ViewBag.Success = true;
        ViewBag.Message = "Employee successfully added";
        return RedirectToAction("Index");
    }

这行不通。有可能把这样的东西包装在一个分部中吗?或者MVC去掉了<script>标签吗?我可以在视图上的脚本块中渲染部分吗?

我甚至试图将脚本标记中的代码直接移动到View,然后在Controller上设置值,结果似乎什么都没发生。

有什么帮助吗?视图再次渲染时ViewBag是否已清除?我应该使用TempData吗?我可以将SuccessMessage属性移动到我的ViewModel中,然后像这样将其传递到我的View中吗?

public ActionResult Index(MyViewModel model) 
{
    //Do something with model.Success 
}

我的解决方案

我使用了几个答案来得出我网站这一部分的最终结论,很可能会在其他部分使用公认答案的方法。

我去并添加了以下到我的ViewModel

public bool Success { get; set; } 
public string Message { get; set; } 

在属性全部设置后,我让Action返回带有ViewModel的Index视图

//fetch the updated data and shove into ViewModel here
viewModel.Success = true;
viewModel.Message = "Employee successfully checked in";
return View("Index", viewModel);

然后在我的View 中使用Razor语法

@if (Model.Success) { 
    @:toastr.success("@Model.Message");
} else if (!Model.Success && !String.IsNullOrWhiteSpace(Model.Message)) {
    @:toastr.error("@Model.Message");   
}

还有一个额外的好处(尽管实现看起来很草率),在我的文档中呈现Partial。就绪块

@Html.Partial("_ToastPartial", Model)

并将Toast通知代码移动到部分

@if (Model.Success) { 
    @:toastr.success("@Model.Message");
} else if (!Model.Success && !String.IsNullOrWhiteSpace(Model.Message)) {
    @:toastr.error("@Model.Message");   
}

最有可能的是,我会设置一个具有MessageSuccess属性的接口,并使任何将使用该部分的ViewModels实现该接口

您的控制器正在执行RedirectToAction。ViewBag和ViewData只能在当前请求中幸存。TempData是当你使用重定向时要使用的东西(而且只有在那时):

http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications明确指出:

[…]TempData对象在一个基本场景中运行良好:

  • 在当前和下一个HTTP请求之间传递数据

使用这个nuget包,我很容易在mvc中使用toast。我有点惊讶它没有被更多地使用。。。https://www.nuget.org/packages/RedWillow.MvcToastrFlash

如果您正在寻找ASP上的实现,请尝试此库NtoastNotify。NET核心。(免责声明:作者在这里)