Call Us: (888) 373-8718
Jim SowersNo Comments.NET Programming, Jim Sowers, web

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”


The Layout or Master Page

If you are using razor with mvc, you can put this in your _layout:

<input type="hidden" id="success" value="@TempData["success"]"/>
<input type="hidden" id="info" value="@TempData["info"]"/>
<input type="hidden" id="info" value="@TempData["warning"]"/>
<input type="hidden" id="error" value="@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!!!";

Did you like this? Share it:

Leave a reply

Your email address will not be published. Required fields are marked *

Back to Top