5
\$\begingroup\$

This code works great, but I think it can be reduced.

@if (Session["Success"] != null)
{
 <text>
 <div class="alert alert-success">@Session["Success"]</div>
 </text>
 Session.Remove("Success");
}
else if (Session["Error"] != null)
{
 <text>
 <div class="alert alert-danger">@Session["Error"]</div>
 </text>
 Session.Remove("Error");
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Dec 15, 2013 at 13:58
\$\endgroup\$
1
  • 1
    \$\begingroup\$ What should happen when Session contains both "Success" and "Error"? Should that behave exactly the same as your code (i.e. print the success case)? Or is that situation impossible? \$\endgroup\$ Commented Dec 15, 2013 at 15:05

1 Answer 1

6
\$\begingroup\$

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

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();
 <text>
 <div class="alert alert-@alertClass">@Model.Message</div>
 </text>
}

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.

answered Dec 15, 2013 at 17:45
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.