将子目录添加到“查看/共享” ASP.Net MVC 中的文件夹并调用视图

发布于 2024-10-17 04:27:46 字数 400 浏览 1 评论 0原文

我目前正在使用 ASP.Net MVC3 和 Razor 开发一个网站。在“View/Shared”文件夹中,我想添加一个名为“Partials”的子文件夹,我可以在其中放置所有部分视图(为了更好地组织网站。

只要我始终这样做,我就可以毫无问题地执行此操作调用视图时引用“Partials”文件夹(使用 Razor):

@Html.Partial("Partials/{ViewName}")

我的问题是是否有办法将“Partials”文件夹添加到 .Net 在搜索视图时经过的列表中,这样我就可以调用我的视图查看而不必引用“Partials”文件夹,如下所示:

@Html.Partial("{ViewName}")

感谢您的帮助!

I'm currently developing a site using ASP.Net MVC3 with Razor. Inside the "View/Shared" folder, I want to add a subfolder called "Partials" where I can place all of my partial views (for the sake of organizing the site better.

I can do this without a problem as long as I always reference the "Partials" folder when calling the views (using Razor):

@Html.Partial("Partials/{ViewName}")

My question is if there is a way to add the "Partials" folder to the list that .Net goes through when searching for a view, this way I can call my view without having to reference the "Partials" folder, like so:

@Html.Partial("{ViewName}")

Thanks for the help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

拔了角的鹿 2024-10-24 04:27:47

解决了这个问题。要将我创建的“Shared/Partials”子目录添加到尝试在 Razor 中查找部分视图时搜索的位置列表中,请使用以下方法:

@Html.Partial("{NameOfView}")

首先创建一个以 RazorViewEngine 作为其基类的视图引擎,然后添加视图位置,如下所示。同样,我想将所有部分视图存储在我在 MVC 创建的默认“Views/Shared”目录中创建的“Partials”子目录中。

public class RDDBViewEngine : RazorViewEngine
{
    private static readonly string[] NewPartialViewFormats = 
    { 
        "~/Views/{1}/Partials/{0}.cshtml",
        "~/Views/Shared/Partials/{0}.cshtml"
    };

    public RDDBViewEngine()
    {
        base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NewPartialViewFormats).ToArray();
    }       

}

请注意,位置格式中的 {1} 是控制器名称,{0} 是视图名称。

然后将该视图引擎添加到 global.asax 中的 Application_Start() 方法中的 MVC ViewEngines.Engines 集合中:

ViewEngines.Engines.Add(new RDDBViewEngine()); 

Solved this. To add the "Shared/Partials" sub directory I created to the list of locations searched when trying to locate a Partial View in Razor using:

@Html.Partial("{NameOfView}")

First create a view engine with RazorViewEngine as its base class and add your view locations as follows. Again, I wanted to store all of my partial views in a "Partials" subdirectory that I created within the default "Views/Shared" directory created by MVC.

public class RDDBViewEngine : RazorViewEngine
{
    private static readonly string[] NewPartialViewFormats = 
    { 
        "~/Views/{1}/Partials/{0}.cshtml",
        "~/Views/Shared/Partials/{0}.cshtml"
    };

    public RDDBViewEngine()
    {
        base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NewPartialViewFormats).ToArray();
    }       

}

Note that {1} in the location format is the Controller name and {0} is the name of the view.

Then add that view engine to the MVC ViewEngines.Engines Collection in the Application_Start() method in your global.asax:

ViewEngines.Engines.Add(new RDDBViewEngine()); 
寄意 2024-10-24 04:27:47

谢谢您的回答。这已经组织好了我的共享文件夹,但是为什么要创建一个新类型的视图引擎呢?我刚刚创建了一个新的 RazorViewEngine,设置它的 PartialViewLocationFormats 并将其添加到 ViewEngines 列表中。

ViewEngines.Engines.Add(new RazorViewEngine
{
    PartialViewLocationFormats = new string[]
    {
        "~/Views/{1}/Partials/{0}.cshtml",
        "~/Views/Shared/Partials/{0}.cshtml"
    }
});

Thank you for your answers. This has organized my Shared folder, but why do you create a new type of view engine? I just made a new RazorViewEngine, set it's PartialViewLocationFormats and added it to the list of ViewEngines.

ViewEngines.Engines.Add(new RazorViewEngine
{
    PartialViewLocationFormats = new string[]
    {
        "~/Views/{1}/Partials/{0}.cshtml",
        "~/Views/Shared/Partials/{0}.cshtml"
    }
});
伴梦长久 2024-10-24 04:27:47

自定义视图引擎很好,但如果您只想有一个部分视图的子文件夹,则不需要那么多...

只需使用部分视图的完整路径,就像布局视图所做的那样:

@Html.Partial("/Views/Shared/Partial/myPartial.cshtml")

希望如此帮助某人...

It´s nice to custom the view engine, but if you just want to have a subfolder por partials you don´t need that much...

Just use the full path to the partial view, as done for the Layout View:

@Html.Partial("/Views/Shared/Partial/myPartial.cshtml")

Hope it helps someone...

∝单色的世界 2024-10-24 04:27:47

如果您在 ASP.NET Core 中执行此操作,只需转到 Startup 类的 ConfigureServices 方法下,然后将

services.AddMvc()
    .AddRazorOptions(opt => {
        opt.ViewLocationFormats.Add("/Views/{1}/Partials/{0}.cshtml");
        opt.ViewLocationFormats.Add("/Views/Shared/Partials/{0}.cshtml");
    });

If you are doing this in ASP.NET Core, simple go to the Startup class, under ConfigureServices method, and put

services.AddMvc()
    .AddRazorOptions(opt => {
        opt.ViewLocationFormats.Add("/Views/{1}/Partials/{0}.cshtml");
        opt.ViewLocationFormats.Add("/Views/Shared/Partials/{0}.cshtml");
    });
桃气十足 2024-10-24 04:27:47

我已经更新了 lamarant 的优秀答案以包含区域:

public class RDDBViewEngine : RazorViewEngine
{
    private static readonly string[] NewPartialViewFormats =
    {
        "~/Views/{1}/Partials/{0}.cshtml",
        "~/Views/Shared/Partials/{0}.cshtml"
    };

    private static List<string> AreaRegistrations;

    public RDDBViewEngine()
    {
        AreaRegistrations = new List<string>();

        BuildAreaRegistrations();

        base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NewPartialViewFormats).ToArray();
        base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(areaRegistrations).ToArray();
    }

    private static void BuildAreaRegistrations()
    {
        string[] areaNames = RouteTable.Routes.OfType<Route>()
            .Where(d => d.DataTokens != null && d.DataTokens.ContainsKey("area"))
            .Select(r => r.DataTokens["area"].ToString()).ToArray();

        foreach (string areaName in areaNames)
        {
            AreaRegistrations.Add("~/Areas/" + areaName + "/Views/Shared/Partials/{0}.cshtml");
            AreaRegistrations.Add("~/Areas/" + areaName + "/Views/{1}/Partials/{0}.cshtml");
        }
    }
}

然后不要忘记在您的应用程序开始中包含:

public class MvcApplication : System.Web.HttpApplication
{

    protected void Application_Start()
    {
        ...

        ViewEngines.Engines.Add(new RDDBViewEngine()); 
    }
}

I've updated lamarant's excellent answer to include Areas:

public class RDDBViewEngine : RazorViewEngine
{
    private static readonly string[] NewPartialViewFormats =
    {
        "~/Views/{1}/Partials/{0}.cshtml",
        "~/Views/Shared/Partials/{0}.cshtml"
    };

    private static List<string> AreaRegistrations;

    public RDDBViewEngine()
    {
        AreaRegistrations = new List<string>();

        BuildAreaRegistrations();

        base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NewPartialViewFormats).ToArray();
        base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(areaRegistrations).ToArray();
    }

    private static void BuildAreaRegistrations()
    {
        string[] areaNames = RouteTable.Routes.OfType<Route>()
            .Where(d => d.DataTokens != null && d.DataTokens.ContainsKey("area"))
            .Select(r => r.DataTokens["area"].ToString()).ToArray();

        foreach (string areaName in areaNames)
        {
            AreaRegistrations.Add("~/Areas/" + areaName + "/Views/Shared/Partials/{0}.cshtml");
            AreaRegistrations.Add("~/Areas/" + areaName + "/Views/{1}/Partials/{0}.cshtml");
        }
    }
}

Then don't forget to include in your application start:

public class MvcApplication : System.Web.HttpApplication
{

    protected void Application_Start()
    {
        ...

        ViewEngines.Engines.Add(new RDDBViewEngine()); 
    }
}
潇烟暮雨 2024-10-24 04:27:47

您还可以更新注册的 RazorViewEngine 的partialview-location-formats。
将以下代码放置在 Global.asax 的 Application_Start 中。

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

You can also update the partialview-location-formats of the registered RazorViewEngine.
Place the below code in Application_Start in Global.asax.

 RazorViewEngine razorEngine = ViewEngines.Engines.OfType<RazorViewEngine>().FirstOrDefault();
        if (razorEngine != null)
        {
            string[] newPartialViewFormats = new[] { 
                    "~/Views/{1}/Partials/{0}.cshtml",
                    "~/Views/Shared/Partials/{0}.cshtml"
            };
            razorEngine.PartialViewLocationFormats =
                razorEngine.PartialViewLocationFormats.Union(newPartialViewFormats).ToArray();
        }
蓝梦月影 2024-10-24 04:27:47

您可以创建注册您自己的视图引擎,该引擎派生自您正在使用的任何视图引擎(Webforms/Razor),并在构造函数中指定您想要的任何位置,或者只是将它们添加到现有位置的列表中:

this.PartialViewLocationFormats = viewLocations;

然后在应用程序启动中您将添加你的视图引擎就像这样:
ViewEngines.Engines.Add(new MyViewEngineWithPartialPath());

You can create register your own view engine that derives from whatever view engine your are using (Webforms/Razor) and specify whatever locations you want in the constructor or just add them to the list of already existing locations:

this.PartialViewLocationFormats = viewLocations;

Then in application start you would add your view engine like so:
ViewEngines.Engines.Add(new MyViewEngineWithPartialPath());

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文