Render partial from different folder (not shared)

前端 未结 10 1924
名媛妹妹
名媛妹妹 2020-11-29 17:12

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

相关标签:
10条回答
  • 2020-11-29 17:35

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

    0 讨论(0)
  • 2020-11-29 17:39

    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.

    Add a class to your Models folder:

    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:

    ViewEngines.Engines.Add(new NewViewEngine());
    
    0 讨论(0)
  • 2020-11-29 17:39

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

    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

    0 讨论(0)
  • 2020-11-29 17:40

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

    Razor:

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

    ASP.NET engine:

    <% 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?

    0 讨论(0)
提交回复
热议问题