加载目录中的所有部分

时间:2013-09-13 14:30:42

标签: c# asp.net-mvc-4 razor-2

我有这个:

Views/MyView/_partials
   ... partial1.cshtml
   ... partial2.cshtml
   ... partial3.cshtml

我正在加载它们:

<div>
    @Html.Partial("_partials/partial1.cshtml")
    @Html.Partial("_partials/partial2.cshtml")
    @Html.Partial("_partials/partial3.cshtml")
</div>

有没有办法加载该目录中的所有文件?

1 个答案:

答案 0 :(得分:1)

string virtual_path = Server.MapPath("~/Views/MyView/_partials");   

DirectoryInfo directory = new DirectoryInfo(virtual_path); 
FileInfo[] filesInDir = directory.GetFiles("*.cshtml"); 
List<string> list = new List<string>(); 

foreach (FileInfo foundFile in filesInDir) 
{ 
    list.Add(Path.Combine(foundFile.Directory.Name, Path.GetFileNameWithoutExtension(foundFile.Name))); 
}

您可以获取此类文件并将其传递给ViewBag,以便在视图中使用

@foreach (string file in ViewBag.OptionsFiles) 
{ 
  @Html.Partial(file) 
}