我在我的MVC应用程序中使用Toastr通知插件来显示状态消息(成功的编辑、更新、删除等),我想知道是否有一种简单的方法来在Partial视图中放置一些逻辑并将其放在我的Layout或每个单独的视图中。
Partial
<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");
}
Controller
public ActionResult SomethingAwesome(MyViewModel model)
{
ViewBag.Success = true;
ViewBag.Message = "Employee successfully added";
return RedirectToAction("Index");
}
这不起作用。是否可能将像这样的内容包装在部分中,或者MVC会剥离<script>
标记?我能否在View中的脚本块内呈现部分?
我甚至尝试直接将代码移动到View中的脚本标记中,然后在Controller上设置值,似乎什么也没有发生。
需要帮助吗?当视图再次呈现时,ViewBag是否被清除?我应该使用TempData吗?我可以将Success
和Message
属性移入我的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);
然后在我的视图中使用Razor语法即可。
@if (Model.Success) {
@:toastr.success("@Model.Message");
} else if (!Model.Success && !String.IsNullOrWhiteSpace(Model.Message)) {
@:toastr.error("@Model.Message");
}
作为额外的奖励(尽管实现似乎有些粗糙),在我的document.Ready块中呈现Partial。
@Html.Partial("_ToastPartial", Model)
将Toastr通知代码移动到局部视图中
@if (Model.Success) {
@:toastr.success("@Model.Message");
} else if (!Model.Success && !String.IsNullOrWhiteSpace(Model.Message)) {
@:toastr.error("@Model.Message");
}
最有可能的是我会设置一个接口,其中包含 Message
和 Success
属性,并使任何将使用部分实现该接口的 ViewModel 实现它
type="text/javascript"
,并且您的 JavaScript 中缺少引号:@:toastr.success("@ViewBag.Message")
。 - nemesvready
函数中插入alert('@ViewBag.Message')
来调试你的 ViewBag 是否有消息。 - Pete