Message
Helper for MVC Application
public
static
class
MessageExtensions
{
public
enum
MessageType
{
Success
= 0,
Info
= 1,
Warning
= 2,
Error
= 3
}
public
static
void
ShowMessage(this
Controller
controller, MessageType
messageType, string
message, bool
showAfterRedirect = false)
{
string
messageTypeKey = messageType.ToString();
if
(showAfterRedirect)
{
controller.TempData[messageTypeKey]
= message;
}
else
{
controller.ViewData[messageTypeKey]
= message;
}
}
public
static
HtmlString
RenderMessages(this
HtmlHelper
htmlHelper, bool
clearMessage = true)
{
string
messages = String.Empty;
foreach
(string
messageType in
Enum.GetNames(typeof(MessageType)))
{
object
message = htmlHelper.ViewContext.ViewData.ContainsKey(messageType)
?
htmlHelper.ViewContext.ViewData[messageType]
:
htmlHelper.ViewContext.TempData.ContainsKey(messageType)
?
htmlHelper.ViewContext.TempData[messageType]
:
null;
if
(message != null)
{
string
_class = string.Empty;
var
spanTag = new
TagBuilder("span");
if
(messageType == MessageType.Success.ToString())
{
//_class
= "success";
_class
= "alert-success";
//spanTag.SetInnerText("Success!
");
}
else
if
(messageType == MessageType.Error.ToString())
{
//_class
= "error";
_class
= "alert-danger";
//
spanTag.SetInnerText("Error! ");
}
else
if
(messageType == MessageType.Info.ToString())
{
_class
= "information";
//
spanTag.SetInnerText("Information! ");
}
else
if
(messageType == MessageType.Warning.ToString())
{
//_class
= "warning";
_class
= "alert-warning";
//spanTag.SetInnerText("Warning!
");
}
var
messageBoxBuilder = new
TagBuilder("div");
messageBoxBuilder.Attributes["onclick"]
= "$(this).fadeOut(3000)";
messageBoxBuilder.AddCssClass(string.Format("msg
{0}",
_class));
string
close = "<a
class='notification-close' href='javascript:'>×</a>";
messageBoxBuilder.InnerHtml
= spanTag + message.ToString() + close;
messages
+= messageBoxBuilder.ToString();
ClearMessages(htmlHelper,
messageType);
}
}
return
MvcHtmlString.Create(messages);
}
private
static
void
ClearMessages(HtmlHelper
htmlHelper, string
messageType)
{
htmlHelper.ViewContext.ViewData[messageType]
= htmlHelper.ViewContext.TempData[messageType] = null;
}
}
How to use this
Message Helper
1. Add this in you
view
@Html.RenderMessages(true)
2.Set
message from controller
ShowMessage(MessageExtensions.MessageType.Error,
"Mail
has not been sent.",
true);
Comments
Post a Comment