将可选对象传递给所有视图

Dyn*_*nde 0 c# asp.net asp.net-mvc razor asp.net-mvc-3

所以,基本上我想做的是做一些事情:

@if(Notification!=null){
     //perform javascript notification with @Notification.Text
 }
Run Code Online (Sandbox Code Playgroud)

我希望能够在任何视图上执行此操作,因此我将始终可以选择在我的控制器操作中指定通知对象,如果已定义,则可以在视图中处理.

我的梦想场景是通过以某种方式创建Notification对象,然后只返回视图来允许这个.意思是,我不需要将Notification对象显式传递给模型.像这样:

public ActionResult MyAction(){
    Notification n = new Notification("Text for javascript");
    return View();
}
Run Code Online (Sandbox Code Playgroud)

我在想,有些方法可以通过一些ViewPage继承来实现这一点吗?但我真的不确定如何解决这个问题?

在一个理想的世界里,我也希望能够"超越"做什么.例如,如果我在'top'-layout中选择执行某种jquery通知,如果通知对象存在,但可能在某些其他嵌套视图中想要以不同方式处理它,我想要覆盖的选项顶层布局处理对象.

我知道这最后一件事可能有点乌托邦(我刚刚开始使用MVC和Razor),但它会很酷:)

Dar*_*rov 7

您可以编写一个自定义全局操作过滤器,它将在所有视图上注入此信息.例如:

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.Controller.ViewBag.Notification = new Notification("Text for javascript");                 
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在RegisterGlobalFilters您的方法中注册此过滤器Global.asax:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new MyActionFilterAttribute());
}
Run Code Online (Sandbox Code Playgroud)

然后在你的意见中:

@if(ViewBag.Notification != null) 
{
     //perform javascript notification with @ViewBag.Notification.Text
}
Run Code Online (Sandbox Code Playgroud)