patterncsharpMinor
Displaying alert from an action
Viewed 0 times
fromalertactiondisplaying
Problem
This code works great, but I think it can be reduced.
@if (Session["Success"] != null)
{
@Session["Success"]
Session.Remove("Success");
}
else if (Session["Error"] != null)
{
@Session["Error"]
Session.Remove("Error");
}Solution
It's a bad idea to modify the session state from inside a view or a partial view. Instead, I would create an alert view model
and use that from inside the view/partial view, for example:
This way, you avoid modifying the session where someone else may not expect it, and you have a cleaner view.
About populating the view: I do not know why you are using the session, but if the value is only needed for one request, you should consider using
public class AlertViewModel
{
public AlertType AlertType { get; set; }
public string Message { get; set; }
}
public enum AlertType
{
None,
Success,
Error
}and use that from inside the view/partial view, for example:
@if (Model.AlertType != AlertType.None)
{
string alertClass = Model.AlertType.ToString().ToLowerInvariant();
@Model.Message
}This way, you avoid modifying the session where someone else may not expect it, and you have a cleaner view.
About populating the view: I do not know why you are using the session, but if the value is only needed for one request, you should consider using
TempData instead. In any way, just populate the view model in the controller and remove the session value if you need to.Code Snippets
public class AlertViewModel
{
public AlertType AlertType { get; set; }
public string Message { get; set; }
}
public enum AlertType
{
None,
Success,
Error
}@if (Model.AlertType != AlertType.None)
{
string alertClass = Model.AlertType.ToString().ToLowerInvariant();
<text>
<div class="alert alert-@alertClass">@Model.Message</div>
</text>
}Context
StackExchange Code Review Q#37414, answer score: 6
Revisions (0)
No revisions yet.