【问题标题】:CSHTML files not loading outside of ViewsCSHTML 文件未在视图之外加载
【发布时间】:2015-03-11 18:26:30
【问题描述】:

我有一个 C# MVC Razor 站点。通常,控制器从 Views 文件夹加载视图。但是,我有一种特殊情况,我需要在 Views 文件夹之外渲染视图。我该怎么做?

  • 控制器将加载 /Views/Random/Index.cshtml

  • 无法加载 /Random/Index.cshtml

  • /Random/test.aspx 加载没有问题,但是不能将cshtml文件改成aspx文件,需要定期构建。

我试过在Controller中return Redirect("/Random/Index.cshtml"),目前根本没有控制器。

奇怪的是它适用于我的生产环境,但不适用于 localhost。在 localhost 我得到:

您请求的页面类型没有被提供,因为它已被明确禁止。扩展名“.cshtml”可能不正确。请检查下面的 URL 并确保其拼写正确。

请求的 URL:/Random/Index.cshtml

【问题讨论】:

  • 为什么你需要那个?它会给你什么错误?
  • 如果没有 Contoller,它表示 cshtml 文件已被明确禁止。使用控制器,它要么导致无限循环(当我使用重定向时),要么说文件夹不存在(它不在 Views 文件夹中)
  • 请编辑您的问题以包含实际的完整错误。

标签: c# asp.net-mvc-4 razor


【解决方案1】:

你绝对可以做到这一点。为此,您需要创建一个新的自定义视图引擎,例如

public class MyViewEngine : RazorViewEngine
{
    private static string[] AdditionalViewLocations = new[]{
        "~/Random/{0}.cshtml"
    };

    public MyViewEngine()            
    {
        base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(AdditionalViewLocations).ToArray();
        base.ViewLocationFormats = base.ViewLocationFormats.Union(AdditionalViewLocations).ToArray();
        base.MasterLocationFormats = base.MasterLocationFormats.Union(AdditionalViewLocations).ToArray();
    }
}

然后在你 global.asax 的 Application_Start 方法中像这样注册这个视图引擎-

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

如果您希望您的视图引擎优先,则将其插入第 0 位。像这样 -

ViewEngines.Engines.Insert(0, new MyViewEngine());

【讨论】:

    【解决方案2】:

    return View("~/AnotherFolder/Index.cshtml")` 应该适合你。

    不要忘记在索引视图中指明布局:

    @{
       Layout="~/Views/Shared/Layout.cshtml";
    } 
    

    【讨论】:

    • 这行得通,除了我必须在页面顶部添加@inherits System.Web.Mvc.WebViewPage。它也没有加载任何配置,如捆绑配置。我怎样才能做到这一点?就像我希望它像视图中的普通页面一样加载。谢谢!
    • 嗯,我没有这样的问题,我认为它应该像普通视图一样工作,您是否在视图上指定了布局?
    • 我不确定,我只是按照你说的做了:return View("~/Random/Index.cshtml");
    • 尝试在您的视图中添加此广告:@{Layout="~/Views/Shared/Layout.cshtml";}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 2010-11-18
    相关资源
    最近更新 更多