1

嗨,我正在使用 c# 做我的 mvc4 项目。我正在尝试获取目录中的所有子目录。并在我的视图中列出它

为此,我正在编写以下代码

控制器

public ActionResult Gallery()
    {
        string folderpath = Server.MapPath("~/Content/Gallery/GalleryImages");
        List<string> currentimage = new Gallery().GetGalleryName(folderpath);
        //What will be the return type???/
        return View(currentimage);
    }

模型

public List<string> GetGalleryName(string path)
    {
        DirectoryInfo di = new DirectoryInfo(path);
        DirectoryInfo[] subdir = di.GetDirectories();
        List<String> files = new List<String>();
        foreach (DirectoryInfo dir in subdir)
        {
            var name = dir.Name;
            files.Add(name);
        }

        return files;
    }

我的代码是正确的吗?那么控制器和模型中的返回类型是什么?请帮我

4

3 回答 3

1

将控制器中的 foreach 循环更改为

foreach (DirectoryInfo dir in subdir)
        {
            files.Add(dir.Name);
        }

并更改您的控制器

public ActionResult Gallery()
    {
        string folderpath = Server.MapPath("~/Content/Gallery/GalleryImages");
        string[] currentimage = new Gallery().GetGalleryName(folderpath);
        //What will be the return type???/
        return View(currentimage);
    }

public ActionResult Gallery()
    {
        string folderpath = Server.MapPath("~/Content/Gallery/GalleryImages");
        List<String> currentimage = new Gallery().GetGalleryName(folderpath);
        //What will be the return type???/
        return View(currentimage);
    }

我没有尝试过,但这应该可以。希望能帮助到你

于 2013-10-04T04:38:52.583 回答
1

将 foreach 循环更改为以下

 foreach (DirectoryInfo dir in subdir)
    {
                    files.Add(dir.FullName);
    }
于 2013-10-04T04:39:43.763 回答
0

在你的控制器中试试这个

public ActionResult Gallery()
{
  List<String> galleryList = new List<String>();
  string folderpath = Server.MapPath("~/Content/Gallery/GalleryImages");
  string[] currentimage = new Gallery().GetGalleryName(folderpath);
  foreach (var folder in currentimage) {
    galleryList.Add(folder);
  }
return View(galleryList);
}
于 2013-10-04T04:51:20.127 回答