2016-08-07 7 views
0

を説明するいくつかのチュートリアルを読んで、を、ビューフォルダを移動する必要がある場合のビューフォルダのデフォルトパスに置き換えます。しかし、私はどのようにビューエンジンで検索されるパスを追加する方法を把握しようとしています。ASP.NET CoreのViewEngineExpanderで検索場所を追加する

は、ここで私がこれまで持っているものです。

public class BetterViewEngine : IViewLocationExpander 
{ 
    public void PopulateValues(ViewLocationExpanderContext context) 
    { 
    } 

    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) 
    { 
     return viewLocations.Select(s => s.Add("")); //Formerly s.Replace("oldPath", "newPath" but I wish to add 
    } 
} 

そして、私のStartup.cs

services.AddMvc().AddRazorOptions(options => 
     { 
      options.ViewLocationExpanders.Add(new BetterViewEngine()); 
     }); 
+0

を変更したいですビューのデフォルトの場所? –

+0

このポストを参照してください:[ASP.NET MVCでビューを検索するカスタムの場所を指定できます](http://stackoverflow.com/questions/632964/can-i-specify-a-custom-location-to -search-for-views-in-asp-net-mvc) –

答えて

1

であなたがビューを検索するためのデフォルトの動作を変更したい場合は、この試してみてください。

public class BetterViewEngine : IViewLocationExpander 
{ 
    public void PopulateValues(ViewLocationExpanderContext context) 
    { 
     context.Values["customviewlocation"] = nameof(BetterViewEngine); 
    } 

    public IEnumerable<string> ExpandViewLocations(
     ViewLocationExpanderContext context, IEnumerable<string> viewLocations) 
    { 
     return new[] 
     { 
      "/folderName/{1}/{0}.cshtml", 
      "/folderName/Shared/{0}.cshtml" 
     }; 
    } 
} 

ただし、いずれかのフォルダの名前を変更したいだけならこの方法を試してください。

public IEnumerable<string> ExpandViewLocations(
     ViewLocationExpanderContext context, IEnumerable<string> viewLocations) 
{ 

     // Swap /Shared/ for /_Shared/ 
     return viewLocations.Select(f => f.Replace("/Shared/", "/_Shared/")); 

} 
+0

私はデフォルトの場所を変更するつもりはありませんでした。私はちょうどデフォルト以外のもう一つの場所を検索するためにエンジンが必要でした。どちらの場合でも、あなたの例はうまくいくでしょう。ありがとう –

+0

どのように私はビューのパスに追加情報を渡すことができますか?たとえば、次のパスが必要です。 "/folderName/{1}/{0}.{2}.cshtml" {2}は現在のカルチャのプレースホルダです(例:en-US)。私の問題は、存在する場合は "localized"ビュー(/folderName/Home/Index.en-US.cshtml)を返すか、そうでない場合はデフォルトビュー(/folderName/Home/Index.cshtml)を返すことです。この場合、簡単な解決策はありますか?ありがとう。 – Laserson

0

これはちょうどそれが彼の答えの最初の部分を読んだ後、私が行うために必要かを把握するために私に分を取ったので、Sirwanの答えに拡大している:

public class ViewLocationRemapper : IViewLocationExpander 
{ 
    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) 
    { 
     return new[] 
     { 
      "/Views/{1}/{0}.cshtml", 
      "/Views/Shared/{0}.cshtml", 
      "/Views/" + context.Values["admin"] + "/{1}/{0}.cshtml" 
     }; 
    } 

    public void PopulateValues(ViewLocationExpanderContext context) 
    { 
     context.Values["admin"] = "AdminViews"; 
    } 
} 
関連する問題