【问题标题】:How to show directory files in select using razor?如何使用剃刀在选择中显示目录文件?
【发布时间】:2019-01-16 23:55:21
【问题描述】:

使用我当前的以下代码,我可以获取文件并在选择选项中输出它们,但是如果用户在未选择图像的情况下提交表单,则会出现错误 " 对象引用未设置为对象的实例。"

我在模型中有 merch_image 必需。 如何使用 razor 进行以下选择,以免绕过必需项?

控制器:

public ActionResult Create()
    {
        DirectoryInfo dirInfo = new DirectoryInfo(@"//uploads/stamp_images");

        ViewBag.Message = dirInfo.GetFiles().ToList();
        return View();
    }

查看:

<select class="form-control col-sm-3" id="merch_image" name="merch_image">
                        <option selected disabled="disabled">Select</option>

                               @foreach (var item in ViewBag.Message)

                    {
                        <option value="@item.Name"> @item.Name</option>
                    }

    </select>
@Html.ValidationMessageFor(model => model.merch_image, "", new { @class = "text-danger" })

【问题讨论】:

  • 不确定您的 select 列表将如何显示基于上述内容的 array。我没有看到一个循环(尽管@item 建议有一个......)。通常,您会为此使用 @Html.DropDownListFor 助手。另外,处理POST 的代码在哪里?希望它检查 Model.IsValid 是否进行验证检查(在运行引发异常的代码之前)。
  • 抱歉,我只是编辑显示循环

标签: c# asp.net-mvc razor


【解决方案1】:

试试这个代码,首先找到包含图像的文件夹,然后找到你找到的那个 在文件夹中,

                    string ImagePath = Server.MapPath("~/uploads/stamp_images");

                       string FileName = 'xyz' + ".png";
                        //check image file exist or not
                        var filters = new String[] { "png" };
                        var files = GetFilesFrom(ImagePath, filters, false);

                            foreach (var item in files)
                            {
                                if (item.Contains(FileName))
                                {
                                   //return contains image
                                }
                            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多