I’m trying to build a notifications provider (alerts) for my application. Currently I only need to generate notifications between requests, but having this functionality wrapped in a provider will allow me to hook it up to the database later.
I have 3 types of notifications:
public enum NotificationType
{
Success,
Error,
Info
}
and a Notification object:
public class Notification
{
public NotificationType Type { get; set; }
public string Message { get; set; }
}
I would like to put all notifications in List<Notification> and load it into ViewData["Notifications"]
I could then use the helper to read ViewData["Notifications"] and render it:
I want to implement my own NotificationProvider which would maintain the List<Notification> object.
I want the provider to read TempData[“Notifications”] and load it into List<Notification> Notifications variable. I could then load notifications into ViewData[“Notifications”] for my helper to use.
Code below isn’t working but I think it shows what I’m trying to do.
public class NotificationProvider
{
public List<Notification> Notifications { get; set; }
private Controller _controller;
public NotificationProvider(Controller controller /* How to pass controller instance? */)
{
_controller = controller;
if (_controller.TempData["Notifications"] != null)
{
Notifications = (List<Notification>)controller.TempData["Notifications"];
_controller.TempData["Notifications"] = null;
}
}
public void ShowNotification(NotificationType notificationType, string message)
{
Notification notification = new Notification();
notification.Type = notificationType;
notification.Message = message;
Notifications.Add(notification);
_controller.TempData["Notifications"] = Notifications;
}
public void LoadNotifications()
{
_controller.ViewData["Notifications"] = Notifications;
}
}
And in each controller a NotificationProvider instance:
public class HomeController
{
private NotificationProvider notificationProvider;
public HomeController()
{
notificationProvider = new NotificationProvider(/* Controller instance */);
notificationProvider.LoadNotifications();
}
}
Question:
How do I pass the controller instance to NotificationProvider class so it can access TempData and ViewData objects. Or if it’s possible, how can I access those objects directly from NotificationProvider instance?
I think you only want to pass this, like that. Also, back from comments, TempData will only be available in actions: