In my application I have created a base controller. All the other controller derives from BaseController
public class BaseController : Controller
{
//
// GET: /Base/
public void Warning(string message)
{
TempData.Add(Alerts.WARNING, message);
}
public void Success(string message)
{
TempData.Add(Alerts.SUCCESS, message);
}
public void Information(string message)
{
TempData.Add(Alerts.INFORMATION, message);
}
public void Error(string message)
{
TempData.Add(Alerts.ERROR, message);
}
}
No if I derive any other controller from BaseController
it is possible to do this
public ActionResult Test()
{
Success("This is a success Alert");
}
Now in _alert partial view
I check the tempdata and growl it using Toastr.
_alerts partial view
@if (TempData.ContainsKey(Alerts.SUCCESS))
{
foreach (var value in TempData.Values)
{
<script>
toastr.success("@value.ToString()");
</script>
}
}
@if (TempData.ContainsKey(Alerts.ERROR))
{
foreach (var value in TempData.Values)
{
<script>
toastr.error("@value.ToString()");
</script>
}
}
@if (TempData.ContainsKey(Alerts.INFORMATION))
{
foreach (var value in TempData.Values)
{
<script>
toastr.warning("@value.ToString()");
</script>
}
}
@if (TempData.ContainsKey(Alerts.WARNING))
{
foreach (var value in TempData.Values)
{
<script>
toastr.warning("@value.ToString()");
</script>
}
}
this _alert
partial view is renderd in my _layout
view. Which is the main layout of the application.
All all the pages use that layout.
Problem:
The problem i'm facing is, once I send the message from controller, for example:
Success("This is a success message");
I get a nice message in browser. But everytime I go to next page I get the same message, as it still stays in my TempData
.
What can I do to solve this issue?
I probably have to clear the temp data, but where?
I tried clearing TempData from view:
but it doesn't allow me. I get error on browser saying I can only perform assign, increment, decrement and creating object and things like that but not TempData.Clear();
. Also, it would not be good idea to perform clearing TempData in client side, would it?