首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在我的区域内进行FindPartialView搜索?

如何在我的区域内进行FindPartialView搜索?
EN

Stack Overflow用户
提问于 2013-03-16 17:25:34
回答 1查看 3.1K关注 0票数 4

所以我在Global.asax中注册了所有的区域

代码语言:javascript
复制
protected void Application_Start()
{
  AreaRegistration.RegisterAllAreas();
  //...
  RouteConfig.RegisterRoutes(RouteTable.Routes);
}

但是在我的/Areas/Log/Controllers中,当我试图找到一个PartialView

代码语言:javascript
复制
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, "_LogInfo");

它失败了,viewResult.SearchedLocations是:

代码语言:javascript
复制
"~/Views/Log/_LogInfo.aspx"
"~/Views/Log/_LogInfo.ascx"
"~/Views/Shared/_LogInfo.aspx"
"~/Views/Shared/_LogInfo.ascx"
"~/Views/Log/_LogInfo.cshtml"
"~/Views/Log/_LogInfo.vbhtml"
"~/Views/Shared/_LogInfo.cshtml"
"~/Views/Shared/_LogInfo.vbhtml"

因此,viewResult.Viewnull

如何在我的地区进行FindPartialView搜索?

更新:这是我的自定义视图引擎,我已经在Global.asax中注册了它

代码语言:javascript
复制
public class MyCustomViewEngine : RazorViewEngine
{
  public MyCustomViewEngine() : base()
  {
    AreaPartialViewLocationFormats = new[]
    {
      "~/Areas/{2}/Views/{1}/{0}.cshtml",
      "~/Areas/{2}/Views/Shared/{0}.cshtml"
    };

    PartialViewLocationFormats = new[]
    {
      "~/Views/{1}/{0}.cshtml",
      "~/Views/Shared/{0}.cshtml"
    };

  // and the others...
  }
}

但是FindPartialView不使用AreaPArtialViewLocationFormats

代码语言:javascript
复制
"~/Views/Log/_LogInfo.cshtml"
"~/Views/Shared/_LogInfo.cshtml"
EN

回答 1

Stack Overflow用户

发布于 2013-03-16 17:31:57

我也遇到了同样的问题,我使用了一个中央Ajax控制器,在这个控制器中,我从不同的文件夹/位置返回不同的部分视图。

您需要做的是创建一个从ViewEngine派生的新的RazorViewEngine (我假设您使用Razor),并显式地在构造函数中包含新的位置来搜索其中的部分。

或者,您可以重写FindPartialView方法。默认情况下,Shared文件夹和当前控制器上下文中的文件夹用于搜索。

下面是一个示例,它向您展示了如何覆盖自定义RazorViewEngine中的特定属性。

更新

应该在PartialViewLocationFormats数组中包含部分的路径,如下所示:

代码语言:javascript
复制
public class MyViewEngine : RazorViewEngine
{
  public MyViewEngine() : base()
  {
    PartialViewLocationFormats = new string[]
     {
       "~/Area/{0}.cshtml"
       // .. Other areas ..
     };
  }
}

同样,如果要在Area文件夹中的Controller中找到分部,则必须将标准的部分视图位置添加到AreaPartialViewLocationFormats数组中。我已经测试过这个了,它对我很有用。

只需记住将新的RazorViewEngine添加到Global.asax.cs中,例如:

代码语言:javascript
复制
protected void Application_Start()
{
  // .. Other initialization ..
  ViewEngines.Engines.Clear();
  ViewEngines.Engines.Add(new MyViewEngine());
} 

下面是如何在一个名为“Home”的示例控制器中使用它:

代码语言:javascript
复制
// File resides within '/Controllers/Home'
public ActionResult Index()
{
  var pt = ViewEngines.Engines.FindPartialView(ControllerContext, "Partial1");
  return View(pt);
}

我已经将我正在寻找的部分存储在/Area/Partial1.cshtml路径中。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15452312

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档