我正在尝试为我的应用程序构建通知提供程序(警报)。目前我只需要在请求之间生成通知,但是将这个功能包装在提供程序中将允许我稍后将它连接到数据库。
我有3种类型的通知:
public enum NotificationType
{
Success,
Error,
Info
}
和Notification对象:
public class Notification
{
public NotificationType Type { get; set; }
public string Message { get; set; }
}
我想将所有通知放入List<Notification>
并将其加载到ViewData["Notifications"]
然后我可以使用帮助器来读取ViewData["Notifications"]
并渲染它:
我想实现自己的NotificationProvider,它将维护List<Notification>
对象。
我希望提供程序读取TempData [“Notifications”]并将其加载到List<Notification> Notifications
变量中。然后我可以将通知加载到ViewData [“Notifications”]中供我的助手使用。
下面的代码不起作用,但我认为它显示了我正在尝试做的事情。
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;
}
}
在每个控制器中都有一个NotificationProvider实例:
public class HomeController
{
private NotificationProvider notificationProvider;
public HomeController()
{
notificationProvider = new NotificationProvider(/* Controller instance */);
notificationProvider.LoadNotifications();
}
}
问题:
如何将控制器实例传递给NotificationProvider类,以便它可以访问TempData和ViewData对象。或者,如果可能,我如何直接从NotificationProvider实例访问这些对象?
答案 0 :(得分:1)
我认为你只想传递这个,就像那样。此外,从评论返回,TempData仅在操作中可用:
public class HomeController
{
public ActionResult Index()
{
var notificationProvider = new NotificationProvider(this);
notificationProvider.LoadNotifications();
return View();
}
}