如何创建视图以显示ASP.Net MVC 4项目中的文件列表 [英] How to create view to display list of files in ASP.Net MVC 4 project

查看:166
本文介绍了如何创建视图以显示ASP.Net MVC 4项目中的文件列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习ASP.Net MVC 4编程.目前,我想在网页上显示文件列表.以下是我到目前为止所做的事情.

I am learning ASP.Net MVC 4 Programming. Currently, I want to display the list of files to the web page. Following is what I did till now.

HomeController.cs中,我对Contact动作进行了如下

In the HomeController.cs I edited the Contact action as follows:

public ActionResult Contact()
{
     ViewBag.Message = "Your file page.";
     DirectoryInfo dirInfo = new DirectoryInfo(@"c:\");
     List<string> filenames=dirInfo.GetFiles().Select(i=>i.Name).ToList();
     ViewBag.data = filenames; 
     ///^^ Is this correct??    

     return View();
}

我希望文件名显示在网页上.我认为应该写些什么?我右键单击Contact操作并获得默认视图,其中包含:

I want the filenames to be displayed to the web page. What should I write in my view? I right clicked the Contact action and got the default view, containing:

@{
    ViewBag.Title = "Contact";
}

<h2>Contact</h2>

推荐答案

正如@ChrisV所写,您可能想创建一个强类型的视图.这意味着您正在将模型与视图相关联.然后,您将使用View()重载传递数据,该重载将Model作为参数.在当前版本中,您正在使用ViewBag将数据发送到视图.没错,但是至少在学习过程中,最好创建一个强类型的视图.

As @ChrisV wrote, you may want to create a strongly typed view. That means that you're associating a Model with your View. You would then pass the data using the View() overload which takes the Model as parameter. In your current version, you're sending data to the view using the ViewBag. That's not wrong, but it would be probably best to create a strongly typed view, at least as you go along learning.

话虽如此,我可能会进行以下更改:

That being said, I would probably do the following changes:

在您的控制器中,获取FileInfo对象的列表,而不是文件名. FileInfo类型提供了可用于丰富显示数据的其他功能.

In your controller, get a list of FileInfo objects, instead of file names. The FileInfo type exposes additional features that you can use to enrich the displayed data.

public ActionResult Contact()
{
    ViewBag.Message = "Your file page.";
    DirectoryInfo dirInfo = new DirectoryInfo(@"c:\");
    List<FileInfo> files = dirInfo.GetFiles().ToList();

    //pass the data trough the "View" method
    return View(files);
}

接下来,您需要在视图内指定模型类型,并迭代和显示数据:

Next, you need to specify the model type inside your view, and to iterate and display the data:

@model IEnumerable<FileInfo>

@{
     ViewBag.Title = "Contact";
}

<h2>Contact</h2>

<ul>
@foreach (FileInfo file in Model)
{
     <li>@file.Name</li>
}
</ul>

请注意,您实际在页面上显示的内容和方式取决于您.您可以为文件创建一个表,并显示创建时间,大小甚至命令(下载,删除等).这只是一个模板";照这样使用.

Please note, what and how you actually display on the page is up to you. You could create a table for the files and display the creation time, the size or even a command (download, delete, etc.). This is just a "template"; use it as such.

这篇关于如何创建视图以显示ASP.Net MVC 4项目中的文件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆