增值基类属性的ActionFilter [英] Adding value to base class property in ActionFilter

查看:121
本文介绍了增值基类属性的ActionFilter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了自己的网站一个简单的悄悄话系统。下面是模式:

 公共类PrivateMessage:GlobalViewModel
{
    [键]
    公众诠释的MessageId {搞定;组; }    公共BOOL IsRead {搞定;组; }
    公众的DateTime CreatedDate {搞定;组; }
    [MAXLENGTH(100)
    公共字符串主题{搞定;组; }    [MAXLENGTH(2500)]
    公共字符串车身{搞定;组; }    公共虚拟用户配置发件人{搞定;组; }    公共虚拟用户配置接收器{搞定;组; }
}

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

 公共类GlobalViewModel
{
    [NotMapped]
    公共虚拟INT NewMessages {搞定;组; }
}

所有其他的ViewModels从该类继承。为了获得新的私人邮件的数量对于用户来说,我这样做:

 公共覆盖无效OnActionExecuted(ActionExecutedContext filterContext)
    {
        的DbContext DB =新的DbContext();
        INT用户ID =(int)的Membership.GetUser()ProviderUserKey。
        INT newMessages = db.PrivateMessages.Where(A => a.Receiver.UserId ==用户ID和放大器;&安培; a.IsRead ==假).Count之间的();
        base.OnActionExecuted(filterContext);
    }

我来到这个和OnActionExecuting的确呼吁每一个动作。但我的问题是:

如何在newMessages添加到GlobalViewModel?

我想最终做的,就是把这种在主视图会发生什么

 你有@ Model.NewMessages新消息


解决方案

您可以覆盖<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onactionexecuted%28v=vs.98%29.aspx\"相对=nofollow> OnActionExecuted 它运行后,你的行动已经完成运行和这将允许您检查模型传递给视图,并可能修改事件它通过它设置一些属性:

 公共类PrivateMessageFilterAttribute:ActionFilterAttribute
{
    公共覆盖无效OnActionExecuting(ActionExecutedContext filterContext)
    {
        GlobalViewModel模型= NULL;        VAR的ViewResult = filterContext.Result为ViewResultBase;
        如果(的ViewResult!= NULL)
        {
            //动作返回的ViewResult或PartialViewResult
            //所以我们可以尝试读取已传递模型
            模型= viewResult.Model为GlobalViewModel;
        }        如果(型号== NULL)
        {
            VAR jsonResult = filterContext.Result为JsonResult;
            如果(jsonResult!= NULL)
            {
                //动作返回JsonResult
                //所以我们可以尝试读取已传递模型
                模型= jsonResult.Data为GlobalViewModel;
            }
        }        如果(型号!= NULL)
        {
            //我们已经成功地读取模型
            //现在我们可以设置其属性NewMessages
            model.NewMessages = GetNewMessages();
        }
    }    私人诠释GetNewMessages()
    {
        INT用户id =(int)的Membership.GetUser()ProviderUserKey。
        INT newMessages = db.PrivateMessages.Where(A =&GT; a.Receiver.UserId ==用户用户名与放大器;&安培; a.IsRead ==假).Count之间的();
    }
}

作为替代使用,你可以写一个自定义的HTML帮助将返回此信息的基本视图模式。

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 OnActionExecuted event 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:

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

As an alternative to using a base view model you could write a custom HTML helper which will return this information.

这篇关于增值基类属性的ActionFilter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆