有人有如何将文件名放入 ASP.NET Core MVC Razor 页面上的下拉列表中的示例吗?

问题描述 投票:0回答:1

enter image description here

enter image description here

这正在 ASP.NET Core 6 MVC 应用程序中使用。

这里是一些手动执行此操作的代码,但我需要读取文件夹文件名并让它们填充下拉列表。我对此很陌生,因此非常感谢任何帮助。

 <dd class="col-sm-10">
     <select name="PHOTO1" id="PHOTO1" class="form-control">
         <option value="USA">USA</option>
         <option value="UK">UK</option>
         <option value="Japan">Japan</option>
         <option value="France">France</option>
     </select>
     <span asp-validation-for="PHOTO1" class="text-danger"></span>
</dd>
razor asp.net-core-mvc
1个回答
0
投票

在从文件系统读取文件的情况下,我建议您注入 IWebHostEnvironment 接口,然后使用

WebRootPath
属性解析
wwwroot
文件夹的绝对文件路径,然后就可以用于获取子文件和子文件夹,例如您的
user_images
文件夹:

@inject IWebHostEnvironment env;

<select name="PHOTO1" id="PHOTO1" class="form-control">
    @{
        var userImagesDirName = "user_images";
        var userImagesPath = System.IO.Path.Combine(env.WebRootPath, userImagesDirName);
        var userImagesDir = new DirectoryInfo(userImagesPath);
        var userImagesFiles = userImagesDir.GetFiles();
    }
    @foreach (FileInfo fi in userImagesFiles) {
        @* Then use the @Url.Content helper to resolve a HTTP link to the file path *@
        <option value="fi">@Url.Content($"~/{userImagesDirName}/{fi.Name}")</option>
    }
</select>

© www.soinside.com 2019 - 2024. All rights reserved.