2012-02-15 79 views
0

首先有一点上下文。当你调用Html.RenderPartial您发送的视图名称,这一观点将在由RazorViewEngine.PartialViewLocationFormats指定位置搜索:如何设置剃刀布局文件,只需指定名称?

Html.RenderPartial("Post", item); 

当您设置在剃刀页面布局属性,你不容只是说这个名字,你需要指定路径。我怎样才能指定名称?

//Layout = "_Layout.cshtml"; 
Layout = "_Layout"; //Dont work 

我需要这个,因为我重写了RazorViewEngine.MasterLocationFormats。

目前我在控制器指定网站站长:

return View("Index", "_Layout", model); 

这工作,但我更喜欢在查看做到这一点。

+2

看这个问题http://stackoverflow.com/questions/5357104/is-is-possible-to-specify-searchable- location-formats-for-mvc-razor-layout – sarvesh 2012-02-15 02:05:08

回答

1

没有直接的办法做到这一点, 但我们可以写像“的RenderPartial()”,这将在运行时给完成布局路径的HtmlExtension。

public static class HtmlExtensions 
{ 
    public static string ReadLayoutPath<T>(this HtmlHelper<T> html,string layoutName) 
    { 
     string[] layoutLocationFormats = new string[] { 
     "~/Views/{1}/{0}.cshtml", 
      "~/Views/Shared/{0}.cshtml" 
     }; 

     foreach (var item in layoutLocationFormats) 
     {     
      var controllerName= html.ViewContext.RouteData.Values["Controller"].ToString(); 
      var resolveLayoutUrl = string.Format(item, layoutName, controllerName); 
     string fullLayoutPath = HostingEnvironment.IsHosted ? HostingEnvironment.MapPath(resolveLayoutUrl) : System.IO.Path.GetFullPath(resolveLayoutUrl); 
     if (File.Exists(fullLayoutPath)) 
      return resolveLayoutUrl; 
     } 
     throw new Exception("Page not found."); 
    } 
} 

在我们可以使用它作为视图,

@{ 
Layout = Html.ReadLayoutPath("_Layout"); 
} 
0

我可以问你为什么这么做,或者更具体一点,你为什么要从控制器返回布局页面?你似乎错过了母版页的重点。

你不能指定只是“名称”,你需要指定布局视图的路径,以便它可以反过来应用到视图正在渲染。

Layout = "~/SomeCustomLocation/SomeFolder/_Layout.cshtml" 
+1

我没有从控制器返回,这是我找到的解决方法。如果我不能指定名称,RazorViewEngine.MasterLocationFormats的目的是什么? – 2012-02-15 10:17:11

+0

这样做有一些合理的原因。例如,您的主网站上有一个插件项目,您希望允许使用完全不同的wwwroot等 – rolls 2017-10-19 03:35:05