Coder Perfect

Make a partial render from a different folder (not shared)

Problem

How do I get a view to render a partial (user control) from another folder? I used to be able to call RenderUserControl with the full route in preview 3, but this is no longer available with preview 5. Instead, we get the RenderPartial method, which doesn’t provide the functionality I need.

Asked by Boris Callens

Solution #1

Simply include the file extension and the path of the view.

Razor:

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

ASP.NET engine:

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

If that’s not the case, could you perhaps share the code you used with the RenderUserControl?

Answered by Elijah Manor

Solution #2

In my scenario, I was using MvcMailer (https://github.com/smsohan/MvcMailer) and needed to retrieve a partial view from a folder that wasn’t in the “Shared” folder. The previous methods failed, but utilizing a relative path did.

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

Answered by Aaron Sherman

Solution #3

You can fix this permanently without having to specify the path all of the time if you use this other path frequently. It checks for partial views in the View folder and the Shared folder by default. However, let’s imagine you wish to add one.

To your Models folder, add the following class:

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 add the following line to your Global.asax.cs file:

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

Answered by Paul

Solution #4

Try this if you’re using ASP.NET Core 2.1 or later and want to use the Partial Tag Helper syntax:

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

The tilde () is not required.

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/partial information? It’s also useful to use view=aspnetcore-3.1#partial-tag-helper.

Answered by Theophilus

Solution #5

Write the following for a user control named myPartial.ascx in the Views/Account folder:

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

Answered by Rahatur

Post is based on https://stackoverflow.com/questions/208421/render-partial-from-different-folder-not-shared