4

だから私はすべてのエリアを登録しますGlobal.asax

protected void Application_Start()
{
  AreaRegistration.RegisterAllAreas();
  //...
  RouteConfig.RegisterRoutes(RouteTable.Routes);
}

しかし、私の中/Areas/Log/Controllersで、私が見つけようとするとPartialView

ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, "_LogInfo");

失敗しますviewResult.SearchedLocations

"~/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.Viewですnull

FindPartialView自分のエリアで検索するにはどうすればよいですか?

更新:これは私が登録したカスタムビューエンジンですGlobal.asax

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

"~/Views/Log/_LogInfo.cshtml"
"~/Views/Shared/_LogInfo.cshtml"
4

1 に答える 1

2

私はまったく同じ問題を抱えていました。使用している中央の Ajax コントローラーがあり、さまざまなフォルダー/場所からさまざまな部分ビューを返します。

あなたがしなければならないことは、 aViewEngineから派生した新しいものを作成しRazorViewEngine(Razorを使用していると仮定しています)、コンストラクターに新しい場所を明示的に含めて、パーシャルを検索することです。

または、メソッドをオーバーライドできますFindPartialView。デフォルトでは、Sharedフォルダと現在のコントローラ コンテキストのフォルダが検索に使用されます。

カスタム 内の特定のプロパティをオーバーライドする方法を示す例を次に示しRazorViewEngineます。

アップデート

次のように、PartialViewLocationFormats 配列にパーシャルのパスを含める必要があります。

public class MyViewEngine : RazorViewEngine
{
  public MyViewEngine() : base()
  {
    PartialViewLocationFormats = new string[]
     {
       "~/Area/{0}.cshtml"
       // .. Other areas ..
     };
  }
}

同様に、フォルダー内のコントローラーでパーシャルを見つけたい場合は、標準のパーシャル ビューの場所を配列Areaに追加する必要があります。AreaPartialViewLocationFormats私はこれをテストしましたが、それは私のために働いています。

newRazorViewEngineを に追加することを忘れないでくださいGlobal.asax.cs。例:

protected void Application_Start()
{
  // .. Other initialization ..
  ViewEngines.Engines.Clear();
  ViewEngines.Engines.Add(new MyViewEngine());
} 

「ホーム」と呼ばれる例示的なコントローラーで使用する方法は次のとおりです。

// File resides within '/Controllers/Home'
public ActionResult Index()
{
  var pt = ViewEngines.Engines.FindPartialView(ControllerContext, "Partial1");
  return View(pt);
}

探しているパーシャルを/Area/Partial1.cshtmlパスに保存しました。

于 2013-03-16T17:31:57.533 に答える