Adding Rails like Flash Message in ASP.NET MVC

Rails has a built-in feature called flash which is very handy to show some arbitrary messages after you redirect user to an another page. But so far ASP.NET MVC does not have anything like that. In this post, I will show you, how I added a similar feature in ASP.NET MVC. Lets say you are are working on some CRUD features of User Management and when a user is created you want to redirect to the details page where you want show the message “User was successfully created”, if you are working in Rails you will write something like the following:


              def create
                  @user = User.create(params[:user])
                  redirect_to user_path(@user), :notice => "User was successfully created."
              end
              

And in ASP.NET here is the equivalent:


              public ActionResult Create(User user)
              {
                  userRepository.Create(user);
              
                  RedirectToAction("Details", new { id = user.Id }).WithFlash(new { notice = "User was successfully created." });
              }
              

Though the code is bit noisy comparing to the Rails version, but I guess that we have to live with as C# is not a dynamic language like Ruby.

So what is happening behind the scene? Well the WithFlash is an extension method, which wraps an existing ActionResult and returns a new wrapped ActionResult, it also accepts a Dictionary or an anonymous object like many other methods of ASP.NET MVC. This extension method is only applied for view and redirecting results as the other does not make any sense in this case. Now, when the ActionResult is executed it puts the message in the TempDataDictionary before executing the wrapped ActionResult so the messages are only available for the next request(unless you are executing a view). In the view you will only have to use a single statement Html.Flash which is also an extension method of HtmlHelper. This method will be responsible to dump all the messages from the TempDataDictionary. Here is the code of this extension method:


              public static IHtmlString Flash(this HtmlHelper instance, string tagName = "p", bool encoded = true)
              {
                  Func<string, XNode> content = message => encoded ? new XText(message) : XElement.Parse(message) as XNode;
              
                  var messages = new FlashStorage(instance.ViewContext.TempData).Messages.ToList();
              
                  var elements = messages.Select(pair => new XElement(tagName, new XAttribute("class", "flash" + " " + pair.Key), content(pair.Value)));
                  var html = string.Join(Environment.NewLine, elements.Select(e => e.ToString()));
              
                  return instance.Raw(html);
              }
              

Yes I am using the XLinq instead of the TagBuilder, now when it is called, it will render the following:


              <p class="flash notice">
                  User was successfully created.
              </p>
              

As you can see, it is emitting the flash and the type of the message as css classes, so that we can add some css rules to style those elements. For example ,with some basic styling we can show the flash messages like the following:

Flash messages

That's it for today, you can download the complete code from the following link.

Download: FlashMessage.zip

Shout it

Comments

blog comments powered by Disqus