Search code examples
c#asp.net-mvc-4razor-2

Load all partials in a directory


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?


Solution

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