C# 从不同的文件夹渲染部分(不共享)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/208421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:07:07  来源:igfitidea点击:

Render partial from different folder (not shared)

c#asp.net-mvcrenderpartial

提问by Boris Callens

How can I have a view render a partial (user control) from a different folder? With preview 3 I used to call RenderUserControl with the complete path, but whith upgrading to preview 5 this is not possible anymore. Instead we got the RenderPartial method, but it's not offering me the functionality I'm looking for.

如何让视图呈现来自不同文件夹的部分(用户控件)?在预览 3 中,我曾经使用完整路径调用 RenderUserControl,但是升级到预览 5 这不再可能了。相反,我们获得了 RenderPartial 方法,但它没有提供我正在寻找的功能。

采纳答案by Elijah Manor

Just include the path to the view, with the file extension.

只需包含视图的路径和文件扩展名。

Razor:

剃刀:

@Html.Partial("~/Views/AnotherFolder/Messages.cshtml", ViewData.Model.Successes)

ASP.NET engine:

ASP.NET 引擎:

<% Html.RenderPartial("~/Views/AnotherFolder/Messages.ascx", ViewData.Model.Successes); %>

If that isn't your issue, could you please include your code that used to work with the RenderUserControl?

如果这不是您的问题,能否请您包含用于使用 RenderUserControl 的代码?

回答by Andrew Stanton-Nurse

The VirtualPathProviderViewEngine, on which the WebFormsViewEngine is based, is supposed to support the "~" and "/" characters at the front of the path so your examples above should work.

WebFormsViewEngine 所基于的 VirtualPathProviderViewEngine 应该支持路径前面的“~”和“/”字符,因此上面的示例应该可以工作。

I noticed your examples use the path "~/Account/myPartial.ascx", but you mentioned that your user control is in the Views/Account folder. Have you tried

我注意到您的示例使用路径“~/Account/myPartial.ascx”,但您提到您的用户控件位于 Views/Account 文件夹中。你有没有尝试过

<%Html.RenderPartial("~/Views/Account/myPartial.ascx");%>

<%Html.RenderPartial("~/Views/Account/myPartial.ascx");%>

or is that just a typo in your question?

或者这只是你问题中的一个错字?

回答by Rahatur

For a user control named myPartial.ascx located at Views/Account folder write like this:

对于位于 Views/Account 文件夹中的名为 myPartial.ascx 的用户控件,如下所示:

<%Html.RenderPartial("~/Views/Account/myPartial.ascx");%>

回答by mounir

you should try this

你应该试试这个

~/Views/Shared/parts/UMFview.ascx

place the ~/Views/before your code

将 放在~/Views/您的代码之前

回答by Siva Kandaraj

Try using RenderAction("myPartial","Account");

尝试使用 RenderAction("myPartial","Account");

回答by Jacob

I've created a workaround that seems to be working pretty well. I found the need to switch to the context of a different controller for action name lookup, view lookup, etc. To implement this, I created a new extension method for HtmlHelper:

我创建了一个似乎运行良好的解决方法。我发现需要切换到不同控制器的上下文以进行操作名称查找、视图查找等。为了实现这一点,我创建了一个新的扩展方法HtmlHelper

public static IDisposable ControllerContextRegion(
    this HtmlHelper html, 
    string controllerName)
{
    return new ControllerContextRegion(html.ViewContext.RouteData, controllerName);
}

ControllerContextRegionis defined as:

ControllerContextRegion定义为:

internal class ControllerContextRegion : IDisposable
{
    private readonly RouteData routeData;
    private readonly string previousControllerName;

    public ControllerContextRegion(RouteData routeData, string controllerName)
    {
        this.routeData = routeData;
        this.previousControllerName = routeData.GetRequiredString("controller");
        this.SetControllerName(controllerName);
    }

    public void Dispose()
    {
        this.SetControllerName(this.previousControllerName);
    }

    private void SetControllerName(string controllerName)
    {
        this.routeData.Values["controller"] = controllerName;
    }
}

The way this is used within a view is as follows:

在视图中使用它的方式如下:

@using (Html.ControllerContextRegion("Foo")) {
    // Html.Action, Html.Partial, etc. now looks things up as though
    // FooController was our controller.
}

There may be unwanted side effects for this if your code requires the controllerroute component to not change, but in our code so far, there doesn't seem to be any negatives to this approach.

如果您的代码要求controller不更改路由组件,则可能会产生不必要的副作用,但到目前为止,在我们的代码中,这种方法似乎没有任何负面影响。

回答by Aaron Sherman

In my case I was using MvcMailer (https://github.com/smsohan/MvcMailer) and wanted to access a partial view from another folder, that wasn't in "Shared." The above solutions didn't work, but using a relative path did.

就我而言,我使用的是 MvcMailer (https://github.com/smsohan/MvcMailer) 并想从另一个文件夹访问部分视图,该文件夹不在“共享”中。上述解决方案无效,但使用相对路径有效。

@Html.Partial("../MyViewFolder/Partials/_PartialView", Model.MyObject)

回答by Paul

If you are using this other path a lot of the time you can fix this permanently without having to specify the path all of the time. By default, it is checking for partial views in the View folder and in the Shared folder. But say you want to add one.

如果您经常使用其他路径,则可以永久修复此问题,而无需一直指定路径。默认情况下,它会检查 View 文件夹和 Shared 文件夹中的部分视图。但是说你想加一个。

Add a class to your Models folder:

在 Models 文件夹中添加一个类:

public class NewViewEngine : RazorViewEngine {

   private static readonly string[] NEW_PARTIAL_VIEW_FORMATS = new[] {
      "~/Views/Foo/{0}.cshtml",
      "~/Views/Shared/Bar/{0}.cshtml"
   };

   public NewViewEngine() {
      // Keep existing locations in sync
      base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NEW_PARTIAL_VIEW_FORMATS).ToArray();
   }
}

Then in your Global.asax.cs file, add the following line:

然后在您的 Global.asax.cs 文件中,添加以下行:

ViewEngines.Engines.Add(new NewViewEngine());

回答by Demian Berisford-Maynard

Create a Custom View Engine and have a method that returns a ViewEngineResult In this example you just overwrite the _options.ViewLocationFormatsand add your folder directory :

创建一个自定义视图引擎并有一个返回 ViewEngineResult 的方法在本例中,您只需覆盖_options.ViewLocationFormats并添加您的文件夹目录:

public ViewEngineResult FindView(ActionContext context, string viewName, bool isMainPage)
        {
            var controllerName = context.GetNormalizedRouteValue(CONTROLLER_KEY);
            var areaName = context.GetNormalizedRouteValue(AREA_KEY);

            var checkedLocations = new List<string>();
            foreach (var location in _options.ViewLocationFormats)
            {
                var view = string.Format(location, viewName, controllerName);
                if (File.Exists(view))
                {
                    return ViewEngineResult.Found("Default", new View(view, _ViewRendering));
                }
                checkedLocations.Add(view);
            }

            return ViewEngineResult.NotFound(viewName, checkedLocations);
        }

Example: https://github.com/AspNetMonsters/pugzor

示例:https: //github.com/AspNetMonsters/pugzor

回答by Theophilus

For readers using ASP.NET Core 2.1 or later and wanting to use Partial Tag Helpersyntax, try this:

对于使用 ASP.NET Core 2.1 或更高版本并希望使用Partial Tag Helper语法的读者,请尝试以下操作:

<partial name="~/Views/Folder/_PartialName.cshtml" />

The tilde (~) is optional.

波浪号 (~) 是可选的。

The information at https://docs.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-3.1#partial-tag-helperis helpful too.

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-3.1#partial-tag-helper上的信息也很有帮助。