私はMVCを初めて使用します。私の問題は、これを正しい方法で行っていないという懸念です。現在、期待どおりに機能していますが、構造とメソッドの配置場所がわかりません。
と呼ばれるビュー(ビューモデル?)への表示を支援するために使用しているクラスがあります。FolderFileList
これには、と呼ばれる関数も含まれていますGetFolderStructure()
。この関数は、パスとフォルダーを受け取り、すべてのファイルとフォルダーのリストを作成することをループします。その後、それらを返します。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace xxx.Models
{
public class FolderFileList
{
public DirectoryInfo Directory { get; set; }
public FileInfo File { get; set; }
public List<FileInfo> FileList { get; set; }
public List<DirectoryInfo> FolderList { get; set; }
public List<DirectoryInfo> RootFolderList { get; set; }
public string FolderRoot { get; set;
}
public static FolderFileList GetFolderStructure(string path, string foldername)
{
//initialise variables
DirectoryInfo selecteddirectory = null;
DirectoryInfo rootdirectory = null;
var files = new List<FileInfo>();
var listoffilesandfolders = new FolderFileList();
listoffilesandfolders.FileList = new List<FileInfo>();
listoffilesandfolders.FolderList = new List<DirectoryInfo>();
listoffilesandfolders.RootFolderList = new List<DirectoryInfo>();
listoffilesandfolders.FolderRoot = foldername;
//get selected directory
try
{
selecteddirectory = new DirectoryInfo(path + foldername);
listoffilesandfolders.FolderList = selecteddirectory.GetDirectories("*", SearchOption.AllDirectories).ToList();
}
catch (DirectoryNotFoundException exp)
{
throw new Exception("Could not open the directory", exp);
}
catch (IOException exp)
{
throw new Exception("Failed to access directory", exp);
}
//get root directory
try
{
rootdirectory = new DirectoryInfo(path);
listoffilesandfolders.RootFolderList = rootdirectory.GetDirectories("*", SearchOption.TopDirectoryOnly).ToList();
}
catch (DirectoryNotFoundException exp)
{
throw new Exception("Could not open the directory", exp);
}
catch (IOException exp)
{
throw new Exception("Failed to access directory", exp);
}
//get all files and subfolder files
try
{
files = selecteddirectory.GetFiles("*", SearchOption.AllDirectories).ToList();
}
catch (FileNotFoundException exp)
{
throw new Exception("Could not find file", exp);
}
catch (IOException exp)
{
throw new Exception("Failed to access fie", exp);
}
files = files.OrderBy(f => f.Name).ToList();
foreach (FileInfo file in files)
{
listoffilesandfolders.FileList.Add(file);
}
return listoffilesandfolders;
}
}
私のコントローラー:
public ActionResult Folder(string foldername)
{
var path = Server.MapPath(@"~\");
var folderstructure = FolderFileList.GetFolderStructure(path, foldername);
return View(folderstructure);
}
私の質問は次のとおりです。
- このクラスはどこに置くのですか?現在、モデル フォルダにあります。
- メソッドはクラスに依存しているのですが、クラスに入れてもいいですか?どうすればいいですか?