如何使用 MEF 在 MVC 3 Razor 中渲染控件

发布于 2024-11-30 09:20:26 字数 6380 浏览 2 评论 0原文

首先这是我的错误: 找不到类型或命名空间名称“Web”(您是否缺少 using 指令或程序集引用?)

public class _Page_Plugins_Views_Web_Plugins_Controls_Controls_Menu_cshtml : System.Web.Mvc.WebViewPage<Web.Plugins.Controls.Models.MenuModel> {

我正在使用 MEF 和强类型视图构建可插入 MVC 3.0 Razor 网站。我让插件工作得很好,直到我开始构建菜单。菜单是它自己的一个插件。我用过 http://www.thegecko.org/index.php/2010/06/pluggable-mvc-2-0-using-mef-and-strongly-typed-views/comment-page-1/ #comment-7130。到目前为止,一切都很好,就像我提到的那样,但是当我在布局中渲染菜单时,它会弹出一个错误(请参见上面)。

下面是实现此操作的代码。为什么它尝试渲染视图而不仅仅是部分视图?

我的控制器:

[HandleError]
[ControllerMetaData("Controls")]
[Export(typeof(IController)), PartCreationPolicy(CreationPolicy.NonShared)]
public class ControlsController : MefController
{
    public virtual ActionResult Menu()
    {
        var builder = new MenuModelBuilder(Context.MenuContainer);
        ViewData.Model = builder.BuildModel();

        return PartialView();
    }

}

我的_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Web.Plugins.Presentation/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/Web.Plugins.Presentation/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/Web.Plugins.Presentation/modernizr-1.7.min.js")" type="text/javascript"></script>
</head>
<body>
<div class="page">
    <header>
        <div id="title">
            <h1>My MVC Application</h1>
        </div>
        <div id="logindisplay">
            @Html.Partial("_LogOnPartial")
        </div>
        <nav>
            <ul id="menu">
                @*<li>@Html.ActionLink("Home", "Index", "Home")</li>
                <li>@Html.ActionLink("About", "About", "Home")</li>*@


                @{
                    Html.Action("Menu", "Controls");
                }
            </ul>
        </nav>
    </header>
    <section id="main">
        @RenderBody()
    </section>
    <footer>
    </footer>
</div>

我的 MefViewEngine.cs

public class MefViewEngine : RazorViewEngine
{
    private readonly string _defaultMaster;

    public MefViewEngine(string pluginPath, IEnumerable<IPluginRegistration> plugins, string defaultMaster)
    {
        _defaultMaster = defaultMaster;
        CreateViewLocations(pluginPath, plugins);
    }

    public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
    {
        // Set default master page
        if (string.IsNullOrWhiteSpace(masterName) && !controllerContext.IsChildAction)
        {
            masterName = _defaultMaster;
        }

        // Ensure name is correct
        if (masterName.ToLowerInvariant().EndsWith(".cshtml"))
        {
            masterName = masterName.ToLowerInvariant().Replace(".cshtml", string.Empty);
        }

        if (string.IsNullOrWhiteSpace(masterName))
        {
            return base.FindPartialView(controllerContext, viewName, useCache);
            //masterName = _defaultMaster;
        }
        return base.FindView(controllerContext, viewName, masterName, useCache);
    }

    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
    {
        // If view isn't .aspx, remove master page
        if (!viewPath.ToLowerInvariant().EndsWith(".cshtml"))
        {
            masterPath = string.Empty;
        }

        var nameSpace = controllerContext.Controller.GetType().Namespace;
        //return base.CreateView(controllerContext, viewPath.Replace("%1", nameSpace), masterPath.Replace("%1", nameSpace));

        return base.CreateView(controllerContext, viewPath, masterPath);
    }

    #region Helper Methods

    private void CreateViewLocations(string pluginPath, IEnumerable<IPluginRegistration> plugins)
    {
        IList<string> viewLocations = new List<string>();
        IList<string> masterLocations = new List<string>();
        string pluginLocation;

        foreach (IPluginRegistration plugin in plugins)
        {
            pluginLocation = string.Format("~/{0}/Views/{1}/", pluginPath, plugin.AssemblyName);
            AddViewLocation(viewLocations, pluginLocation);
            AddMasterLocation(masterLocations, pluginLocation);
        }

        pluginLocation = "~/Views/";
        AddViewLocation(viewLocations, pluginLocation);

        ViewLocationFormats = viewLocations.ToArray();
        PartialViewLocationFormats = viewLocations.ToArray();
        MasterLocationFormats = masterLocations.ToArray();

        AreaViewLocationFormats = new[] {
            "~/" + pluginPath + "/Views/{2}/{1}/{0}.cshtml",
            "~/" + pluginPath + "/Views/{2}/{1}/{0}.cshtml",
            "~/" + pluginPath + "/Views/{2}/Shared/{0}.cshtml",
            "~/" + pluginPath + "/Views/{2}/Shared/{0}.cshtml",
        };

        AreaPartialViewLocationFormats = AreaViewLocationFormats;

        AreaMasterLocationFormats = new[] {
            "~/" + pluginPath + "/Views/{2}/{1}/{0}.cshtml",
            "~/" + pluginPath + "/Views/{2}/Shared/{0}.cshtml",
        };
    }

    private static void AddViewLocation(IList<string> viewLocations, string pluginLocation)
    {
        viewLocations.Add(pluginLocation + "{1}/{0}.cshtml");
        viewLocations.Add(pluginLocation + "{1}/{0}.cshtml");
        viewLocations.Add(pluginLocation + "Shared/{0}.cshtml");
        viewLocations.Add(pluginLocation + "Controls/{0}.cshtml");
        viewLocations.Add(pluginLocation + "Shared/{0}.cshtml");
    }

    private static void AddMasterLocation(IList<string> viewLocations, string pluginLocation)
    {
        viewLocations.Add(pluginLocation + "{0}.cshtml");
        viewLocations.Add(pluginLocation + "{1}/{0}.cshtml");
        viewLocations.Add(pluginLocation + "Shared/{0}.cshtml");
    }

    #endregion
}

First here is my error:
The type or namespace name 'Web' could not be found (are you missing a using directive or an assembly reference?)

public class _Page_Plugins_Views_Web_Plugins_Controls_Controls_Menu_cshtml : System.Web.Mvc.WebViewPage<Web.Plugins.Controls.Models.MenuModel> {

I am building a pluggable MVC 3.0 Razor website using MEF and strongly-typed views. I am getting the plugins to work just fine until I get to the building of the menu. The Menu is a plugin of its own. I have used http://www.thegecko.org/index.php/2010/06/pluggable-mvc-2-0-using-mef-and-strongly-typed-views/comment-page-1/#comment-7130. So far all is well like I mentioned but when I go to render the menu in the layout it pops an error (see it above).

Below is the code that gets this going. Why is it trying to render a view and not just the partial?

My Controller:

[HandleError]
[ControllerMetaData("Controls")]
[Export(typeof(IController)), PartCreationPolicy(CreationPolicy.NonShared)]
public class ControlsController : MefController
{
    public virtual ActionResult Menu()
    {
        var builder = new MenuModelBuilder(Context.MenuContainer);
        ViewData.Model = builder.BuildModel();

        return PartialView();
    }

}

My _Layout.cshtml

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Web.Plugins.Presentation/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/Web.Plugins.Presentation/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/Web.Plugins.Presentation/modernizr-1.7.min.js")" type="text/javascript"></script>
</head>
<body>
<div class="page">
    <header>
        <div id="title">
            <h1>My MVC Application</h1>
        </div>
        <div id="logindisplay">
            @Html.Partial("_LogOnPartial")
        </div>
        <nav>
            <ul id="menu">
                @*<li>@Html.ActionLink("Home", "Index", "Home")</li>
                <li>@Html.ActionLink("About", "About", "Home")</li>*@


                @{
                    Html.Action("Menu", "Controls");
                }
            </ul>
        </nav>
    </header>
    <section id="main">
        @RenderBody()
    </section>
    <footer>
    </footer>
</div>

My MefViewEngine.cs

public class MefViewEngine : RazorViewEngine
{
    private readonly string _defaultMaster;

    public MefViewEngine(string pluginPath, IEnumerable<IPluginRegistration> plugins, string defaultMaster)
    {
        _defaultMaster = defaultMaster;
        CreateViewLocations(pluginPath, plugins);
    }

    public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
    {
        // Set default master page
        if (string.IsNullOrWhiteSpace(masterName) && !controllerContext.IsChildAction)
        {
            masterName = _defaultMaster;
        }

        // Ensure name is correct
        if (masterName.ToLowerInvariant().EndsWith(".cshtml"))
        {
            masterName = masterName.ToLowerInvariant().Replace(".cshtml", string.Empty);
        }

        if (string.IsNullOrWhiteSpace(masterName))
        {
            return base.FindPartialView(controllerContext, viewName, useCache);
            //masterName = _defaultMaster;
        }
        return base.FindView(controllerContext, viewName, masterName, useCache);
    }

    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
    {
        // If view isn't .aspx, remove master page
        if (!viewPath.ToLowerInvariant().EndsWith(".cshtml"))
        {
            masterPath = string.Empty;
        }

        var nameSpace = controllerContext.Controller.GetType().Namespace;
        //return base.CreateView(controllerContext, viewPath.Replace("%1", nameSpace), masterPath.Replace("%1", nameSpace));

        return base.CreateView(controllerContext, viewPath, masterPath);
    }

    #region Helper Methods

    private void CreateViewLocations(string pluginPath, IEnumerable<IPluginRegistration> plugins)
    {
        IList<string> viewLocations = new List<string>();
        IList<string> masterLocations = new List<string>();
        string pluginLocation;

        foreach (IPluginRegistration plugin in plugins)
        {
            pluginLocation = string.Format("~/{0}/Views/{1}/", pluginPath, plugin.AssemblyName);
            AddViewLocation(viewLocations, pluginLocation);
            AddMasterLocation(masterLocations, pluginLocation);
        }

        pluginLocation = "~/Views/";
        AddViewLocation(viewLocations, pluginLocation);

        ViewLocationFormats = viewLocations.ToArray();
        PartialViewLocationFormats = viewLocations.ToArray();
        MasterLocationFormats = masterLocations.ToArray();

        AreaViewLocationFormats = new[] {
            "~/" + pluginPath + "/Views/{2}/{1}/{0}.cshtml",
            "~/" + pluginPath + "/Views/{2}/{1}/{0}.cshtml",
            "~/" + pluginPath + "/Views/{2}/Shared/{0}.cshtml",
            "~/" + pluginPath + "/Views/{2}/Shared/{0}.cshtml",
        };

        AreaPartialViewLocationFormats = AreaViewLocationFormats;

        AreaMasterLocationFormats = new[] {
            "~/" + pluginPath + "/Views/{2}/{1}/{0}.cshtml",
            "~/" + pluginPath + "/Views/{2}/Shared/{0}.cshtml",
        };
    }

    private static void AddViewLocation(IList<string> viewLocations, string pluginLocation)
    {
        viewLocations.Add(pluginLocation + "{1}/{0}.cshtml");
        viewLocations.Add(pluginLocation + "{1}/{0}.cshtml");
        viewLocations.Add(pluginLocation + "Shared/{0}.cshtml");
        viewLocations.Add(pluginLocation + "Controls/{0}.cshtml");
        viewLocations.Add(pluginLocation + "Shared/{0}.cshtml");
    }

    private static void AddMasterLocation(IList<string> viewLocations, string pluginLocation)
    {
        viewLocations.Add(pluginLocation + "{0}.cshtml");
        viewLocations.Add(pluginLocation + "{1}/{0}.cshtml");
        viewLocations.Add(pluginLocation + "Shared/{0}.cshtml");
    }

    #endregion
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

坠似风落 2024-12-07 09:20:26

我不了解 MEF,但从我对 MVC 的了解来看,您不应该返回 PartialViewResult 而不是 Action 结果吗?

public virtual PartialViewResult Menu()
{
    var builder = new MenuModelBuilder(Context.MenuContainer);
    ViewData.Model = builder.BuildModel();

    return PartialView();
}

I don't know about MEF but from the little I know about MVC, shouldn't you be returning a PartialViewResult rather than an Action result?

public virtual PartialViewResult Menu()
{
    var builder = new MenuModelBuilder(Context.MenuContainer);
    ViewData.Model = builder.BuildModel();

    return PartialView();
}
执着的年纪 2024-12-07 09:20:26

您是否已将所有命名空间添加到 Views 文件夹中的 web.config 中?您还应该将相同的引用添加到您区域中的 web.config 文件(如果有)。

您在 Razor 视图中创建和引用的任何命名空间都必须添加到元素中包含的命名空间集合中。

Have you added all of your namespaces to the web.config in the Views folder? You should also add the same references to the web.config files in your Areas, if any.

Any namespaces you create and reference in your Razor views must be added to the namespace collection contained in the element.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文