I use the Toastr notification plugin in my MVC application to display status messages (successful editing, updating, deleting, etc.), and I wonder if there is an easy way to put some logic in a partial view and have it on my layout or in every single view where necessary.
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>
View
//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"); }
This does not work. Is it possible to wrap something like this in partial or make MVC cut out <script> tags? Can I make a partial inside a script block in a view?
I even tried moving the code in the script tags directly to the view, and then setting the values ββon the controller, and it seems like nothing is happening.
Any help? Does the ViewBag reset at the time the view is rendered? Should I use TempData? Can I transfer the Success and Message property to my ViewModel and just pass it into my view like this?
public ActionResult Index(MyViewModel model) {
My decision
I used a couple of answers to come to a final conclusion for this section of my site and most likely use the method for the accepted answer in other parts.
I went and added the following to my ViewModel
public bool Success { get; set; } public string Message { get; set; }
I have an action that returns an Index view with a ViewModel, after all properties have been set
//fetch the updated data and shove into ViewModel here viewModel.Success = true; viewModel.Message = "Employee successfully checked in"; return View("Index", viewModel);
And then just use the Razor syntax in my view
@if (Model.Success) { @:toastr.success("@Model.Message"); } else if (!Model.Success && !String.IsNullOrWhiteSpace(Model.Message)) { @:toastr.error("@Model.Message"); }
Just like a bonus (although the implementation seems sloppy) do Partial in my document. Finished block
@Html.Partial("_ToastPartial", Model)
and move the Toastr notification code to partial
@if (Model.Success) { @:toastr.success("@Model.Message"); } else if (!Model.Success && !String.IsNullOrWhiteSpace(Model.Message)) { @:toastr.error("@Model.Message"); }
Most likely, I would install an interface with the Message and Success parameters and create any ViewModels that will use the partially implemented interface