簡體   English   中英

使用目錄中的文件在模式中創建列表框?

[英]Creating a listbox in a modal with files from a directory?

我試圖從目錄中抓取文件,並且我試圖讓用戶從列表中選擇一個文件以供以后處理。

這是獲取文件的代碼。

    [HttpGet]
    public ActionResult GetFiles()
    {
        DirectoryInfo dinfo = new DirectoryInfo(@"C:\TestDirectory");
        List<FileInfo> Files = dinfo.GetFiles("*.txt").ToList();

        return PartialView("_File", Files);
    }

這是現在將在模態中的部分視圖。

@model List<FileInfo>

@Html.ListBoxFor(model => model, new SelectList(Model).AsEnumerable())

我如何從主視圖調用局部視圖:

<div class="row">
<div class="modal fade" id="bootstrapDialog" tabindex="-1" role="dialog" aria-labelledby="myModal-label" aria-hidden="true"></div>
</div>

<div class="btn btn-default browseButton">
<span class="glyphicon glyphicon-folder-open browseDialog" data-url="@Url.Action("GetFiles","Home", null)"></span> 
<span class="browseDialog" data-url="@Url.Action("GetFiles","Home", null)">Browse...</span>
</div>

@section scripts {
<script>
       $(document).ready(function () {

        $('.browseDialog').click(function () {

            var url = $(this).data('url');

            $.get(url, function (data) {

                $('#bootstrapDialog').html(data);

                $('#bootstrapDialog').modal('show');

            });

        });
   });

</script>
}

正在檢索文件信息,但未創建列表框。 列表框給出了一個除了值不能為空或為空。 我是否必須創建其他必須傳遞到此列表框的內容?

我如何允許用戶選擇一個項目以傳遞回屏幕后面的模式以填充文本框?

@model List<FileInfo>new SelectList(Model).AsEnumerable()用法似乎都是錯誤的,因為您沒有指定要在列表中填充的文本和值。 您應該使用如下設置創建一個視圖模型:

public class ViewModel
{
    // other properties

    public string SelectedFile { get; set; }

    // options list
    public IEnumerable<SelectListItem> FilesList { get; set; }
}

然后,在您的控制器操作中,通過使用Select()擴展方法並選擇Name屬性作為選項文本和值,從List<FileInfo>創建List<SelectListItem>實例:

[HttpGet]
public ActionResult GetFiles()
{
    DirectoryInfo dinfo = new DirectoryInfo(@"C:\TestDirectory");
    List<FileInfo> Files = dinfo.GetFiles("*.txt").ToList();

    var model = new ViewModel();

    // use file name to generate option list
    model.FilesList = Files.Select(x => new SelectListItem { Text = x.Name, Value = x.Name }).ToList();

    return PartialView("_File", model);
}

最后,使用從FilesList屬性填充的列表創建一個DropDownListFor助手:

@model ViewModel

@Html.DropDownListFor(model => model.SelectedFile, Model.FilesList, ...)

之后,您可以使用上述string屬性檢索所選文件,例如Server.MapPath()

補充說明:

如果要選擇多個文件名而不是單個文件名,請使用IEnumerable<string>屬性和ListBoxFor助手:

視圖模型

public IEnumerable<string> SelectedFiles { get; set; }

看法

@Html.ListBoxFor(model => model.SelectedFiles, Model.FilesList, ...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM