c# - 如何使用 MEF 在 MVC 3 Razor 中呈现控件

标签 c# asp.net-mvc-3 razor mef

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

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

我正在使用 MEF 和强类型 View 构建一个可插入的 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 .到目前为止,一切都像我提到的那样,但是当我去渲染布局中的菜单时,它会弹出一个错误(见上文)。

下面是执行此操作的代码。为什么它试图呈现一个 View 而不仅仅是部分 View ?

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

我的_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
}

最佳答案

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

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

    return PartialView();
}

关于c# - 如何使用 MEF 在 MVC 3 Razor 中呈现控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7081784/

相关文章:

c# - 重复一段代码来衡量它的执行时间有多稳健?

c# - 用逗号代替小数将数字格式化为字符串

asp.net-mvc-3 - 在 MVC3 项目中使用 Apicontroller

javascript - DateTimePicker 从数据库中预定日期和时间

javascript - 在从 IResultFilter 返回的 Shape View 中调用 Script.Require 在 Orchard CMS 中不起作用?

c# - 无法为表中的标识列插入显式值

c# - 缓存数据列表 asp.net c#

c# - 在 Grid 的 TextBox 中调整字体大小

c# - MVC3 + Entity Framework ,更新实体中的选择性字段

c# - 使用 jquery 调用 C# 方法