2013-03-16 24 views
4

所以我註冊的所有領域中Global.asax如何在我的區域內進行FindPartialView搜索?

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.Viewnull。如何在我的區域搜索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" 

回答

2

我有完全相同同樣的問題,我使用了一箇中央Ajax控制器,其中我從不同的文件夾/位置返回不同的部分視圖。

什麼你將要做的就是創建一個新的ViewEngineRazorViewEngine派生並明確包括新的地點在構造函數來搜索諧音(我是你的使用刀片假設)。

或者您可以覆蓋FindPartialView方法。默認情況下,Shared文件夾和當前控制器上下文文件夾用於搜索。

這是一個example,它向您展示如何覆蓋自定義RazorViewEngine中的特定屬性。

更新

你應該在你的PartialViewLocationFormats部分的路徑列如下:

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

同樣,如果你想找到一個局部的Area文件夾內的一個控制器,那麼你將不得不將標準局部視圖位置添加到AreaPartialViewLocationFormats陣列。我已經測試過這個,它對我有用。

只要記住新RazorViewEngine添加到您的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路徑。

+0

謝謝,能否再詳述一下?我現在有一個自定義視圖引擎,並設置了位置(請參閱我的更新),但FindPartialView不使用它們。任何指針? – 2013-03-16 20:42:36

+0

如果您試圖在正常的MVC位置(即根視圖)中找到Area文件夾中的局部視圖,那麼我認爲您必須添加路徑(〜/ Areas/{2}/Views/{1}/{ 0} .cshtml)添加到PartialViewLocationFormats數組中。 – gdp 2013-03-16 21:56:15

+0

我正在嘗試(〜/ Areas/{2}/Views/{1}/{0} .cshtml),顯示路徑,但viewresult返回值爲null。 – user2156088 2013-05-30 06:30:56

相關問題