Is it possible to have multiple Shared folders in

2019-08-11 11:33发布

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.

2条回答
一纸荒年 Trace。
2楼-- · 2019-08-11 11:45

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

查看更多
趁早两清
3楼-- · 2019-08-11 12:03

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.

查看更多
登录 后发表回答