Toastr and MVC controllers
I often want to generate a message in an .Net MVC controller class and present that to the user with toastr.
Here is a nice pattern for doing just that using TempData.
The Javascript
In a javascript file that is accessible to all the views that are using toastr:
$(document).ready(function() {
if ($('#success').val()) {
displayMessage($('#success').val(), 'success');
}
if ($('#info').val()) {
displayMessage($('#info').val(), 'info');
}
if ($('#warning').val()) {
displayMessage($('#warning').val(), 'warning');
}
if ($('#error').val()) {
displayMessage($('#error').val(), 'error');
}
});
var displayMessage = function (message, msgType) {
toastr.options = {
“closeButton”: false,
“debug”: false,
“positionClass”: “toast-top-right”,
“onClick”: null,
“showDuration”: “300”,
“hideDuration”: “1000”,
“timeOut”: “8000”,
“extendedTimeOut”: “1000”,
“showEasing”: “swing”,
“hideEasing”: “linear”,
“showMethod”: “fadeIn”,
“hideMethod”: “fadeOut”
};
toastr[msgType](message);
};
The Layout or Master Page
If you are using razor with mvc, you can put this in your _layout:
@Html.Hidden(“success”,@TempData[“success”])
@Html.Hidden(“info”,@TempData[“info”])
@Html.Hidden(“warning”,@TempData[“warning”])
@Html.Hidden(“error”,@TempData[“error”])
On my current project, I am working on an older mixed webforms and mvc site so I put this in the views:
<input type="hidden" value="<%=TempData["success"]%>" id="success" />
<input type="hidden" value="<%=TempData["info"]%>" id="info" />
<input type="hidden" value="<%=TempData["warning"]%>" id="warning" />
<input type="hidden" value="<%=TempData["error"]%>" id="error" />
The Controller Code
You send information back from the controller like this:
TempData["warn"] = "You must see this amazing information in a toast!!!";