Flash Messages in MVC

7.2k views Asked by At

I was trying to use flash messages in my MVC project, following these instructions:

I added the package Install-Package FlashMessageExtension by the nuget, and were created some items:

  • FlashMessageExtensions.cs;
  • _Flash.cshtml;
  • jquery.flashmessage.js;
  • jquery.cookie.js;

And as the instructions said, I added it into my _Layout.cshtml:

<script src="@Url.Content("~/Scripts/jquery.cookie.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.flashmessage.js")"></script>
@Html.Partial("_Flash")

In my controller I'm calling:

using MyProject.Extensions;
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name")] Model model)
{
   if (ModelState.IsValid)
   {
       db.Model.Add(model);
       db.SaveChanges();
       return RedirectToAction("Index").Success("Create was successful");
   }
   return View(model);
}

For some reason it isn't working, can someone help me?

ERRORS

SCRIPT5009: 'jQuery' is not defined
jquery.cookie.js, line 60 Character 1

Line: jQuery.cookie = function (key, value, options) {

SCRIPT5009: '$' is not defined
jquery.cookie.js, line 1 Character 1

Line: $.fn.flashMessage = function (options) {

SCRIPT5009: '$' is not defined
Create, line 149 Character 5

Line: $("#flash-messages").flashMessage();

Generated Codes:

jquery.cookie.js

jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

jquery.flashmessage.js

$.fn.flashMessage = function (options) {
    var target = this;
    options = $.extend({}, options, { timeout: 5000, alert: 'alert-info' });

    if (!options.message) {
        setFlashMessageFromCookie(options);
    }

    if (options.message) {
        var alertType = options.alert.toString().toLowerCase();

        if(alertType === "error") {
            alertType = "danger";
        }

        $(target).addClass('alert-' + alertType);

        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;

_Flash.cshtml

<script type="text/javascript">
    $(function () {
        $("#flash-messages").flashMessage();
    });

    $(document).ajaxComplete(function () {
        $("#flash-messages").flashMessage();
    });
</script>
1

There are 1 answers

3
Gabriel Sadaka On

You need to include jQuery as well as the flash message scripts:

<script src="@Url.Content("~/Scripts/jquery.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.cookie.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.flashmessage.js")"></script>

It should have downloaded jQuery with it and make sure jQuery is always loaded before all of the other scripts.