首页 > 解决方案 > 在 Views 文件夹中创建一个视图

问题描述

是否可以.cshtml在 Views(不是 Views 子文件夹)中工作,例如_ViewImports,但我自己的视图。或者是否可以从/Views文件重定向到/Views/Subfolder视图?

我找到了解决方案。您只需要在 Startup.cs 中现有的 MapRoute 之前添加 MapRoute,如下所示:

app.UseMvc(routes =>
            {
                // Short link to a method
                routes.MapRoute(
                    "AnyName",
                    "NameOfYourIActionResult",
                    new {controller = "Controller_Name.cs", action = "IActionResult Method"}
                );

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

标签: c#asp.net-mvc

解决方案


如果您的意思是从另一个位置而不是默认/View文件夹返回视图,是的,这是可能的。

您可以明确指定要使用的视图:

public ActionResult Index()
{
    return View(@"~/Your/View/Location/Index.cshtml");
}

或通过自定义视图引擎:

protected void Application_Start()
{
    RazorViewEngine rve = new RazorViewEngine();
    rve.PartialViewLocationFormats =
        rve.ViewLocationFormats =
            rve.MasterLocationFormats =
                new string[] {
                   "~/Your/View/Location/{1}/{0}.cshtml",
                   "~/Your/View/Location/Shared/{1}/{0}.cshtml"};
     rve.AreaMasterLocationFormats =
        rve.AreaPartialViewLocationFormats =
            rve.AreaViewLocationFormats =
                new string[] {
                   "~/Your/View/Location/Areas/{2}/Views/{1}/{0}.cshtml",
                   "~/Your/View/Location/Areas/{2}/Views/Shared/{1}/{0}.cshtml"};
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(rve);
}

推荐阅读