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.
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();
}
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>
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:
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.
The primary thing you are displaying on the page (i.e. what the view is "for") should be the model. Look up the @model
directive. Here it should be @model List<string>
. Then instead of setting ViewBag.data
, use return View(filenames);
. In your view you will then be able to access a strongly-typed model. If there's anything you don't understand about what I just said, you need to read more about the role of a viewmodel in ASP.NET MVC.