如何提供ASP.NET MVC2母版页与控制器模型indepdent [英] How to provide ASP.NET MVC2 master pages with a model indepdent of the controller

查看:126
本文介绍了如何提供ASP.NET MVC2母版页与控制器模型indepdent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下的ASP.NET MVC2依赖注入强类型的意见和autofac,我试图让通过依赖注入一种常见的动态报头。即我希望这种情况发生,而不认为有要离开这个内容,甚至现有的,我是希望避免容器和手动分辨率静态发现,但我不能找到一种方法来轻松地注入船长或包括局部视图在通过构造函数两种或财产注入的主人。

I'm using strongly typed views and autofac for Dependency Injection under ASP.NET MVC2 and I'm trying to get a common dynamic header via dependency injection. I.e. i want this to happen without the view having to be away of this content even existing and i was hoping to avoid static discovery of the container and manual resolution, but I can't find a way to easily inject the master or a partial view included in the master via either ctor or property injection.

我无法想象这是一种不常见的任务,但我可以在方法上找到的是控制器子类来充填数据到非类型化的ViewData,继承的ViewModels到的东西主数据进入模型或静态解析,所有这一切我想preFER不要使用。我是什么俯瞰?

I can't imagine this is an uncommon task, but all I can find in terms of methods is Controller subclassing to stuff data into untyped ViewData, subclassing ViewModels to stuff master data into the model, or static resolution, all of which I'd prefer not to use. What am I overlooking?

修改:正如已经指出的DI为母版页是战斗的框架。所以我的问题是严重的框架:我真的不关心DI为母版页,但我在现场的铬动态元素,即母版页。与模型提供了它不应该是每个控制器使用主的责任,因为它要求的背景下,没有特定的控制器上下文。我完全承认,直接注射入母版页是不合适的。如果我可以注册一个独立的主控制器除了被调用,那会更好。那可能吗?鉴于向船长提供模型独立于控制器的这个任务,什么是框架恰当的做法?还是在MVC中的共享内容要求每个控制器有了解的内容?

EDIT: As has been pointed out DI into master pages is fighting the framework. So my question is badly framed: I don't really care about DI into master pages, but I have a dynamic element in the chrome of the site, i.e. the master page. Providing it with a model shouldn't be the responsibility of each controller using that master, as it is request context, not controller context specific. I fully admit that injection directly into master pages is inappropriate. If i could register a separate master controller to be invoked in addition, that would be even better. Is that possible? Given this task of providing the master with a model independent of the controller, what is the framework appropriate approach? Or does shared content in MVC require that each Controller has to know about that content?

推荐答案

您可以使用的孩子的行为的。

控制器:

public class MyHeaderController: Controller
{
    private readony IRepository _repository;
    public MyHeaderController(IRepository repository)
    {
        _repository = repository;
    }

    [ChildActionOnly]
    public ActionResult Index() 
    {
        var model = _repository.GetSomeModel();
        return PartialView(model);
    }
}

和地方在你的母版页包含它:

And somewhere in your master page include it:

<div><%= Html.Action("Index", "MyHeader") %></div>

这篇关于如何提供ASP.NET MVC2母版页与控制器模型indepdent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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