-
Notifications
You must be signed in to change notification settings - Fork 1
/
FlashHtmlHelperExtensions.cs
58 lines (51 loc) · 2.17 KB
/
FlashHtmlHelperExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
namespace Santhos.Web.Mvc.BootstrapFlashMessages
{
using System.Text;
using System.Web.Mvc;
/// <summary>
/// Flash HtmlHelper extensions
/// </summary>
public static class FlashHtmlHelperExtensions
{
/// <summary>
/// Gets flash messages partial view
/// </summary>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="dismissible">If set to <c>true</c>, renders flash messages as dismissible.</param>
/// <returns>Flash messages partial view</returns>
public static MvcHtmlString FlashMessages(this HtmlHelper htmlHelper, bool dismissible = false)
{
var stringBuilder = new StringBuilder();
var flashList = GetFlashListFromTempData(htmlHelper);
foreach (Flash flash in flashList)
{
var tagBuilder = new TagBuilder("div");
tagBuilder.MergeAttribute("role", "alert");
tagBuilder.AddCssClass("alert");
tagBuilder.AddCssClass($"alert-{flash.Severity}");
if (dismissible)
{
tagBuilder.AddCssClass("alert-dismissible");
tagBuilder.InnerHtml =
"<button type=\"button\" class=\"close\" " +
"data-dismiss=\"alert\" aria-label=\"Close\">"+
"<span aria-hidden=\"true\">×</span></button>";
}
tagBuilder.InnerHtml += $"<span>{flash.Message}</span>";
stringBuilder.AppendLine(tagBuilder.ToString());
}
flashList.Clear();
return MvcHtmlString.Create(stringBuilder.ToString());
}
/// <summary>
/// Gets the flash list from temporary data.
/// </summary>
/// <param name="htmlHelper">The HTML helper.</param>
/// <returns>Flash list with flash messages</returns>
private static FlashList GetFlashListFromTempData(HtmlHelper htmlHelper)
{
return htmlHelper.ViewContext.TempData[FlashControllerExtensions.FlashTempDataKey] as FlashList
?? new FlashList();
}
}
}