I’m creating a simple Private Message system for my website. Here is the model:
public class PrivateMessage : GlobalViewModel
{
[Key]
public int MessageId { get; set; }
public bool IsRead { get; set; }
public DateTime CreatedDate { get; set; }
[MaxLength(100)]
public string Subject { get; set; }
[MaxLength(2500)]
public string Body { get; set; }
public virtual UserProfile Sender { get; set; }
public virtual UserProfile Receiver { get; set; }
}
I want to check on every page request if you have any new messages, so I can notify the user. Therefore I made a base viewmodel, which contains:
public class GlobalViewModel
{
[NotMapped]
public virtual int NewMessages { get; set; }
}
All other viewmodels inherit from this class. To get the amount of new private messages for the user, I do this:
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
DBContext db = new DBContext();
int userID = (int)Membership.GetUser().ProviderUserKey;
int newMessages = db.PrivateMessages.Where(a => a.Receiver.UserId == userID && a.IsRead == false).Count();
base.OnActionExecuted(filterContext);
}
I came to this and the OnActionExecuting is indeed called on every Action. But my question is:
How can I add the newMessages to the GlobalViewModel?
What I want to eventually do, is call this in the ‘master’ view
You have @Model.NewMessages new messages
You could override the
OnActionExecutedevent which runs after your action has finished running and which would allow you to inspect the model being passed to the view and potentially modify it by setting some properties on it:As an alternative to using a base view model you could write a custom HTML helper which will return this information.