Как визуализировать элемент управления в MVC 3 Razor с помощью MEF - PullRequest
3 голосов
/ 16 августа 2011

Сначала вот моя ошибка: Не удалось найти тип или имя пространства имен «Web» (отсутствует директива using или ссылка на сборку?)

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

Я создаю подключаемый веб-сайт MVC 3.0 Razor, используя MEF и строго типизированные представления. Я заставляю плагины работать нормально, пока не доберусь до создания меню. Меню представляет собой собственный плагин. Я использовал 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>

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
}

Ответы [ 2 ]

0 голосов
/ 22 сентября 2011

Привет, вы смогли решить это?Я не знаю о MEF, но из того, что я знаю о MVC, разве вы не должны возвращать PartialViewResult, а не результат действия

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

    return PartialView();
}
0 голосов
/ 16 августа 2011

Вы добавили все свои пространства имен в файл web.config в папке Views?Вам также следует добавить те же ссылки на файлы web.config в ваших областях, если таковые имеются.

Любые пространства имен, которые вы создаете и на которые ссылаетесь в своих представлениях Razor, должны быть добавлены в коллекцию пространств имен, содержащуюся в элементе.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...