asp.net-mvcpartial-viewsasp.net-mvc-areas

How to load a partial view from ASP.NET MVC application root into area view?


I have an area in my ASP.NET MVC application that needs to make use of partial views stored in the main application.

The code in question is being migrated from the main application into an area for organization, so I need to update the helper tags for the partial views.

Currently my tags look like this:

@await Html.PartialAsync("../Shared/Partials/_details.cshtml")

Of course, this fails in an area, since this helper only begins searching at the Areas/MyArea/ folder. I've tried adding additional ../ to the beginning of the address, but that doesn't change anything. How can I reconnect my partial views to this area?


Solution

  • You need to reference the app root.

    The following example references a partial view from the app root. Paths that start with a tilde-slash (~/) or a slash (/) refer to the app root:

    Partial Tag Helper:

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

    Asynchronous HTML Helper:

    @await Html.PartialAsync("~/Pages/Folder/_PartialName.cshtml")
    @await Html.PartialAsync("/Pages/Folder/_PartialName.cshtml")
    

    https://learn.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-6.0

    See also: significance of tilde sign