What I'm looking to do, is d开发者_JAVA技巧isplay the contents of a folder which is located on my server in a View in my MVC application.
I have what I think should be in place for the Action, however I'm a little unsure how to go about implementing the corresponding view and I was wondering if someone could point be in the right direction on that. (and also, if someone thinks my Action could be improved, advice would be welcome :) )
Here is the action:
public ActionResult Index()
{
DirectoryInfo salesFTPDirectory = null;
FileInfo[] files = null;
try
{
string salesFTPPath = "E:/ftproot/sales";
salesFTPDirectory = new DirectoryInfo(salesFTPPath);
files = salesFTPDirectory.GetFiles();
}
catch (DirectoryNotFoundException exp)
{
throw new FTPSalesFileProcessingException("Could not open the ftp directory", exp);
}
catch (IOException exp)
{
throw new FTPSalesFileProcessingException("Failed to access directory", exp);
}
files = files.OrderBy(f => f.Name).ToArray();
var salesFiles = files.Where(f => f.Extension == ".xls" || f.Extension == ".xml");
return View(salesFiles);
}
Any help would be appreciated, thanks :)
If you only want the file names then you can change your Linq query to
files = files.Where(f => f.Extension == ".xls" || f.Extension == ".xml")
.OrderBy(f => f.Name)
.Select(f => f.Name)
.ToArray();
return View(files);
Then (assuming the default project template) add the following to the Index.cshtml view
<ul>
@foreach (var name in Model) {
<li>@name</li>
}
</ul>
Which will display the list of file names
- IMHO you should expose only what is really needed by the view. Think about it: do you really need to retrieve a whole
FileInfo
object, or only a file path? If the latter is true, just return aIEnumerable<string>
to the view (instead of aIEnumerable<FileInfo>
, which is what you're doing in the above code). Hint: just add aSelect
call to your Linq expression... - Then your view will just render that model - what you need is a foreach loop and some HTML code to do it.
This is a simplified example of a razor view. It will ouput your file names in a HTML table.
@model IEnumerable<FileInfo>
<h1>Files</h1>
<table>
@foreach (var item in Model) {
<tr>
<td>
@item.Name
</td>
</tr>
}
</table>
精彩评论