Instantly share code, notes, and snippets.

Embed
What would you like to do?
ASP.NET MVC Flash Messages (Razor)
<div id="flash-messages" class="alert-message" style="display:none;">
<a class="close" href="#">&times;</a>
<p></p>
</div>
<script type="text/javascript">
$(function () {
$("#flash-messages").flashMessage();
});
</script>
@Html.Partial("_Flash")
// Usage within MVC Controller
[HttpPost]
public ActionResult Create()
{
return RedirectToAction("Index").Success("Message shown to user after redirect");
}
internal static class FlashMessageExtensions
{
public static ActionResult Error(this ActionResult result, string message)
{
CreateCookieWithFlashMessage(Notification.Error, message);
return result;
}
public static ActionResult Warning(this ActionResult result, string message)
{
CreateCookieWithFlashMessage(Notification.Warning, message);
return result;
}
public static ActionResult Success(this ActionResult result, string message)
{
CreateCookieWithFlashMessage(Notification.Success, message);
return result;
}
public static ActionResult Information(this ActionResult result, string message)
{
CreateCookieWithFlashMessage(Notification.Info, message);
return result;
}
private static void CreateCookieWithFlashMessage(Notification notification, string message)
{
HttpContext.Current.Response.Cookies.Add(new HttpCookie(string.Format("Flash.{0}", notification), message) { Path = "/" });
}
private enum Notification
{
Error,
Warning,
Success,
Info
}
}
$.fn.flashMessage = function (options) {
var target = this;
options = $.extend({}, options, { timeout: 3000, alert: 'info' });
if (!options.message) {
setFlashMessageFromCookie(options);
}
if (options.message) {
$(target).addClass(options.alert.toString().toLowerCase());
if (typeof options.message === "string") {
$('p', target).html("<span>" + options.message + "</span>");
} else {
target.empty().append(options.message);
}
} else {
return;
}
if (target.children().length === 0) return;
target.fadeIn().one("click", function () {
$(this).fadeOut();
});
if (options.timeout > 0) {
setTimeout(function () { target.fadeOut(); }, options.timeout);
}
return this;
// Get the first alert message read from the cookie
function setFlashMessageFromCookie() {
$.each(new Array('Success', 'Error', 'Warning', 'Info'), function (i, alert) {
var cookie = $.cookie("Flash." + alert);
if (cookie) {
options.message = cookie;
options.alert = alert;
deleteFlashMessageCookie(alert);
return;
}
});
}
// Delete the named flash cookie
function deleteFlashMessageCookie(alert) {
$.cookie("Flash." + alert, null, { path: '/' });
}
};
@OleHornischer

This comment has been minimized.

OleHornischer commented Aug 2, 2012

To avoid encoding issues for German Umlauts change the method CreateCookieWithFlashMessage in FlashMessageExtensions to

private static void CreateCookieWithFlashMessage(Notification notification, string message)
{
HttpContext.Current.Response.Cookies.Add(new HttpCookie(string.Format("Flash.{0}", notification), HttpUtility.UrlEncode(message)) { Path = "/" });
}

@corneliuskopp

This comment has been minimized.

corneliuskopp commented Apr 22, 2013

Additionally, it seems that in the current state all options given to the method are overwritten with the defaults. Changing

    options = $.extend({}, options, { timeout: 3000, alert: 'info' });

into

    options = $.extend({ timeout: 3000, alert: 'info' }, options);

should preserve user-defined arguments.

@RichardBr

This comment has been minimized.

RichardBr commented Nov 14, 2013

The "jQuery.flashMessage.js" javascript no longer works properly if you use latest version (v1.4.0) of jquery.cookie.js! Hopefully someone who knows javascript will post an update :) By the way, great utility I found it very helpful.

@jimkiely

This comment has been minimized.

jimkiely commented Nov 20, 2013

I like everything that you've done here but I'm getting an error and I can't seem to figure it out.

'System.Web.Mvc.RedirectToRouteResult' does not contain a definition for 'Success' and no extension method 'Success' accepting a first argument of type 'System.Web.Mvc.RedirectToRouteResult' could be found (are you missing a using directive or an assembly reference?)

I created a folder called, Extensions and I put the FlashMessageExtensions.cs file in there. In my controller I have a reference to "MyProject.Extensions".

Any help would be appreciated.

jimkiely@yahoo.com

@thomkaufmann

This comment has been minimized.

thomkaufmann commented Jan 27, 2014

I updated this for jQuery Cookie Plugin v1.4.0 and Bootstrap 3.0.3 here:

https://gist.github.com/thomkaufmann/a1d301789fc3066ebdd5

Please let me know if there are any remaining issues!

@13orno

This comment has been minimized.

13orno commented Aug 13, 2014

Made some change to show multiple message like below.

return RedirectToAction("DashBoard", "agent").Danger("Danger message.").Success("this is a success").Warning("it's a warning");

https://gist.github.com/13orno/d44d0117f17bcd9d0cb7

@MohammadSabbir

This comment has been minimized.

MohammadSabbir commented Sep 4, 2014

whould you please add references.
'System.Web.Mvc.RedirectToRouteResult' does not contain a definition for 'Success' and no extension method 'Success' accepting a first argument of type 'System.Web.Mvc.RedirectToRouteResult' could be found (are you missing a using directive or an assembly reference?
i can't remove this problem

@JKoty

This comment has been minimized.

JKoty commented Apr 22, 2015

MohammadSabbir: you have to have using with extension namespace in your controller.

For example, if your FlashMessageExtensions.cs is in namespace Something.Extensions, you have to add using Something.Extensions; in your controller.

@DaKeZhang7412

This comment has been minimized.

DaKeZhang7412 commented Feb 9, 2017

The "jQuery.flashMessage.js" javascript no longer works properly if you use latest version (v3.1.1) of jquery! Hopefully someone who knows javascript will post an update :) By the way, great utility I found it very helpful.

@siddhant4u

This comment has been minimized.

siddhant4u commented Jul 30, 2018

I'm using one of the fixes done to the original code (by thomkaufmann) and wanted to know the license terms if the code snippet can be used in other projects.

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment