276

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.

Boris Callens
  • 90,659
  • 85
  • 207
  • 305

10 Answers10

481

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?

Pavel Chuchuva
  • 22,633
  • 10
  • 99
  • 115
Elijah Manor
  • 17,923
  • 17
  • 72
  • 79
  • 20
    I wish we could just say /AnotherFolder/Messages – Simon_Weaver Mar 13 '09 at 03:10
  • 5
    @Simon_Weaver You can achieve that. One way would be to modify ViewEngine and override it's `FindPartialView` method with something like `if(partialViewName.Contains"/")partialViewName="~/Views/"+partialViewName;` – Arnis Lapsa Jan 30 '11 at 17:31
  • 2
    Works in the MVC 3 Razor engine as well, but like the above, you need the extension (.cshtml). – Christopher Mar 03 '12 at 07:26
  • If its under different are you would need to give path "~/Areas/TestArea/Views/Shared/_SomePartial.mobile.cshtml" – sandeep talabathula Apr 14 '15 at 17:53
  • How do you handle different cultures of that partial view (for example ~/Views/AnotherFolder/Messages.en.cshtml)? – jasdefer Aug 02 '17 at 15:48
34

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.

@Html.Partial("../MyViewFolder/Partials/_PartialView", Model.MyObject)
Aaron Sherman
  • 3,789
  • 1
  • 30
  • 33
30

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());
Paul
  • 5,700
  • 5
  • 43
  • 67
10

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

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

The tilde (~) is optional.

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

7

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

<%Html.RenderPartial("~/Views/Account/myPartial.ascx");%>
Rahatur
  • 3,147
  • 3
  • 33
  • 49
5

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:

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

ControllerContextRegion is defined as:

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 controller route component to not change, but in our code so far, there doesn't seem to be any negatives to this approach.

Jacob
  • 77,566
  • 24
  • 149
  • 228
4

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.

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

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

or is that just a typo in your question?

Andrew Stanton-Nurse
  • 6,274
  • 1
  • 28
  • 20
0

you should try this

~/Views/Shared/parts/UMFview.ascx

place the ~/Views/ before your code

Liam
  • 27,717
  • 28
  • 128
  • 190
mounir
  • 29
  • 1
0

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

-4

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

Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
Siva Kandaraj
  • 824
  • 7
  • 15
  • 3
    Please Read the question as the user is asking about view in different folder where is folder in your code ? – Pamma Nov 04 '13 at 22:52