我在我的 MVC 应用程序中使用 Toastr 通知插件来显示状态消息(成功编辑、更新、删除等),我想知道是否有一种简单的方法可以将一些逻辑放在部分 View 中,并且将它放在我的布局上或需要时放在每个单独的 View 中。
部分
<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 的脚本 block 中渲染局部吗?
我什至尝试将脚本标签内的代码直接移动到 View ,然后在 Controller 上设置值,但似乎什么都没发生。
有什么帮助吗? View 再次呈现时 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 View
//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");
}
还有一个好处(虽然实现看起来很草率),在我的 document.Ready block 中渲染 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
的接口(interface)和 Success
属性并使任何将使用部分实现该接口(interface)的 ViewModels
最佳答案
您的 Controller 正在执行 RedirectToAction
。 ViewBag 和 ViewData 仅在当前请求中存在。 TempData 是您使用重定向时要使用的东西(并且只有在那时):
http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications明确指出:
[...] the TempData object works well in one basic scenario:
- Passing data between the current and next HTTP requests
关于c# - ASP.NET MVC 中的 Toast 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22972073/