Search code examples
asp.net-corevisual-studio-2019razor-pagespartial-viewsasp.net-mvc-partialview

Setting Partial Page (View) search path in .NET Core Razor Pages and AJAX


I am having a problem setting the 'Search Path' for my Partial Pages (Views) in my .NET Core 3.1 app. When I place the _SomePartialPagePartial.cshtml in the default search path directories (/Pages/Shared/ or /Views/Shared/), or in the same directory as the calling Razor page, the AJAX script calls the public async Task<PartialViewResult> OnPostSomeMethodPartial(string ID, string ID2, ...) and returns the view with return Partial("_SomePartialPagePartial", SomeDataModel) as expected.

But, when I place the _SomePartialPagePartial.cshtml file in another directory, the Razor page cannot find it.

The reason I want to place the Partial Page in another directory is for organizational purposes. I am using Areas to organize the project and would like to keep the partial pages in certain directories. For example, my structure is:

Areas
  Area1
    Models
    Pages
    Partials
    Services
  Area2
    Models
    Pages
    Partials
    Services
etc.

I would like to add a 'Partials' directory to certain Areas (i.e. Areas/Area2/Partials) and place the related partial pages there. The complexity arises when I try to reference a partial page in Areas/Area2/Partials from a Razor Page in Areas/Area1/Pages. In this case, the Razor page CANNOT find the partial file.

I already tried appending the search path in the Startup.cs file (as described in https://www.learnrazorpages.com/razor-pages/partial-pages) but that doesn't seem to work?? The options.PageViewLocationFormats path added via services.Configure<RazorViewEngineOptions>(options => ... does NOT append the path search array as verified in the debugger.

Perhaps the best solution would be to allow setting the directory of the partial file directly in the call (i.e. Partial("<optional path>/_SomePartialPagePartial", SomeDataModel) or Partial("_SomePartialPagePartial", <optional path>, SomeDataModel)). An enhancement?

Anyway, any help/suggestions on how to resolve this would be greatly appreciated... :)

P.S. I am using the latest/updated version of VS 2019 (Version 16.11.3).


Solution

  • You can try to use below code.

    public IActionResult OnPostSomeMethodPartial(string ID, string ID2, ...)
    {
        // var model = new yourModelClass();
        // if you want use model, you can use like below
        // return PartialView("~/Areas/Area1/Partials/testPartialsPage.cshtml",model);
        return PartialView("~/Areas/Area1/Partials/_SomePartialPagePartial.cshtml");
    }
    

    For more details, you can refer below post.

    Application can't find view when using areas