1

In MVC5, I know you can have a Shared folder under Views and then use the RenderPartial to render in partial views.

Is there only ever one Shared folder for the whole website?, or is it possible to have multiple 'Shared' areas?

For instance, I have the following structure on my website:-

\Views

\Views\Shared

\Controllers

\Models

\Identity

\Identity\Views

\Identity\Controllers

\Identity\Models

I was wondering if it would also be possible for the Identity folder to have its own Shared folder as well, that RenderPartial would also work for?

If this is possible, can I render a PartialView from this other Shared folder? I had tried this but wasn't successful - even if I directly reference the View using the tilde ~ approach, but it doesn't seem to like running throwing an exception. However if I put the PartialView in my \Views\Shared folder then everything works.

Community
  • 1
  • 1
Johnny
  • 398
  • 2
  • 18

2 Answers2

1

When rendering PartialViews from other folder rather than the default View folder, you must provide the full path plus the file type:

Ex:

@Html.Partial("~/Identity/Views/myviewname.cshtml")

The way you are doing, looks like you are trying to implement an already existent functionality named Areas.

You should take a look here:

Walk through: Organizing an ASP.NET MVC Application using Areas

Amirhossein Mehrvarzi
  • 18,024
  • 7
  • 45
  • 70
Fals
  • 6,813
  • 4
  • 23
  • 43
  • Perfect. Thankyou. I had not put in the `.cshtml`, I would had thought that would be automatic. – Johnny Oct 26 '14 at 16:56
  • So I assume its only one Shared folder for a website, considering we have to specify a full path to any other partials views used? – Johnny Oct 26 '14 at 16:59
  • 1
    @Johnny you can add your directory in ViewEngine :http://stackoverflow.com/questions/4973000/adding-sub-directory-to-view-shared-folder-in-asp-net-mvc-and-calling-the-view by default it looks in Views directory, but we can add more directories in which Engine should find view – Ehsan Sajjad Oct 26 '14 at 17:06
1

You can include your directories in the ViewEngine by adding following code in Global.asax in Application_Start() event:

RazorViewEngine razorEngine = ViewEngines.Engines.OfType<RazorViewEngine>().FirstOrDefault();
if (razorEngine != null)
{
  string[] newPartialViewFormats = new[] 
          { 
            "~/Indentity/Views/{1}/{0}.cshtml",
            "~/Identity/Views/Shared/{0}.cshtml"
          };

  razorEngine.PartialViewLocationFormats = razorEngine.PartialViewLocationFormats.Union(newPartialViewFormats).ToArray();
 }

Now ViewEngine will find the view in View/Shared and also in Identity/Views/Shared

You can refer this link and also refer this SO Post.

Community
  • 1
  • 1
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160