2013-03-16 26 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

相关问题