How to provide ASP.NET MVC2 master pages with a model indepdent of the controller

瘦欲@ 提交于 2019-12-06 04:11:49

You could use child actions.

Controller:

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>

Your problems stem from confusing the term Dependency Injection, and fighting how the ASP.NET MVC framework works.

Also, you are using the term Dependency Injection in the wrong context. You are trying to use a hammer as a chisel.

MasterPages and views in ASP.NET MVC are intended to be used as templates. As stated in the other answer, child actions will solve your problem.

For future reference:

Dependency Injection refers to a means to configure what parameters to inject into class constructors, and have this done for you automatically, overriding some of the frameworks defaults. The purpose for this is to decouple components, so that they become more reusable, more testable, more unitary, amongst other good things.

DI refers to, and solves, a code issue, not a UI issue.

What you are trying to do is simply not possible. Ie, inject via constructors and properties a "dependency" into a masterpage. Again, MasterPages are intended by ASP.NET MVC to be used as just templates. They have no code behind class to instantiate via a constructor that would allow dependencies to be injected into it.

In other words, you are fighting the framework, which means you don't understand it.

If this sounds like nitpicking, I think this has to be highlighted as otherwise, you are confusing yourself and others who read this thread in the future.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!