Domanda

I have this:

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

And I'm loading them like this:

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

Is there a way to load all files in that directory?

È stato utile?

Soluzione

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))); 
}

You can get the files like this and pass it to the ViewBag so you can use in your view

@foreach (string file in ViewBag.OptionsFiles) 
{ 
  @Html.Partial(file) 
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top