【问题标题】:Populate html.DropDownList with File Names Using GetFiles or EnumarateFiles使用 GetFiles 或 EnumarateFiles 用文件名填充 html.DropDownList
【发布时间】:2016-01-18 13:55:57
【问题描述】:

我正在尝试创建一个非常简单的 HTML.DropDownList 文件。我收到一些无效参数错误。我已经尝试过 GetFiles() 和 EnumerateFiles() 方法。我相信我有一个 IEnumerable 问题。我正在使用 WebMatrix/WebPages/C#。谢谢。

 // DirectoryInfo directory = new DirectoryInfo(Server.MapPath("Images/Products"));
 // var filesListing = directory.GetFiles().ToList<FileInfo>();
 var filesListing = Directory.EnumerateFiles("Images/Products");

 @Html.DropDownList("Files",filesListing)

【问题讨论】:

    标签: asp.net razor html-helper


    【解决方案1】:

    如果是虚拟目录,则需要使用 Server.MapPath...

    var filesListing = Directory.EnumerateFiles(Server.MapPath("Images/Products"));
    @Html.DropDownList("Files",filesListing)
    

    【讨论】:

    • 谢谢。我使用了您的 filesListing 语句,但仍然收到无效参数错误。
    【解决方案2】:

    DropDownList 根本没有这样的过载。您需要使用文件列表构造一个SelectList 对象:

    var filesListing = new SelectList(Directory.EnumerateFiles("Images/Products"));
    

    确保将using System.Web.Mvc; 添加到代码文件中。如果你做了上面的更改,则无需更改视图代码。

    【讨论】:

    • 谢谢,我收到一条缺少的 SelectList 指令消息;我应该添加哪一个?
    • @Edgy 这个位的答案
    • 谢谢,好的,我添加了“@using System.Web.Mvc;”到我的 test.cshtml 页面,但仍然缺少指令消息...而且我没有使用 MVC,谢谢..
    • @Edgy 不使用 MVC 手段?你只使用 asp.net 吗?
    • 我正在使用 Webmatrix 网页 (?)、剃须刀....C#。所以,绝对不要使用 MVC 编码...谢谢..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多