在ActionFilter中向基类属性添加值

时间:2012-12-02 15:21:36

标签: c# asp.net-mvc asp.net-mvc-4

我正在为我的网站创建一个简单的私人消息系统。这是模型:

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; }
}

如果您有任何新消息,我想检查每个页面请求,以便我可以通知用户。因此我制作了一个基本的视图模型,其中包含:

public class GlobalViewModel
{
    [NotMapped]
    public virtual int NewMessages { get; set; }
}

所有其他视图模型都继承自此类。为了获得用户的新私人消息量,我这样做:

    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);
    }

我来到这里,确实在每个Action上都调用了OnActionExecuting。但我的问题是:

如何将newMessages添加到GlobalViewModel?

我最终想做的是在'主'视图中调用它

 You have @Model.NewMessages new messages

1 个答案:

答案 0 :(得分:3)

您可以覆盖在您的操作完成运行后运行的OnActionExecuted事件,这将允许您检查传递给视图的模型,并可能通过在其上设置一些属性来修改它:

public class PrivateMessageFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutedContext filterContext)
    {
        GlobalViewModel model = null;

        var viewResult = filterContext.Result as ViewResultBase;
        if (viewResult != null)
        {
            // The action returned a ViewResult or PartialViewResult
            // so we could attempt to read the model that was passed
            model = viewResult.Model as GlobalViewModel;
        }

        if (model == null)
        {
            var jsonResult = filterContext.Result as JsonResult;
            if (jsonResult != null)
            {
                // The action returned a JsonResult
                // so we could attempt to read the model that was passed
                model = jsonResult.Data as GlobalViewModel;
            }
        }

        if (model != null)
        {
            // We've managed to read the model 
            // Now we can set its NewMessages property
            model.NewMessages = GetNewMessages();
        }
    }

    private int GetNewMessages()
    {
        int userId = (int)Membership.GetUser().ProviderUserKey;
        int newMessages = db.PrivateMessages.Where(a => a.Receiver.UserId == userId && a.IsRead == false).Count();
    }
}

作为使用基本视图模型的替代方法,您可以编写一个自定义HTML帮助程序,它将返回此信息。