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>

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

4

1 回答 1

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) 
}
于 2013-09-13T14:33:48.430 回答