I have a class. In this class I want to list the names of my .txt files in a folder and save them to List<string>
:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace Aplikacja.Models
{
public class Lists
{
public List<string> ListFiles()
{
DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Kamm\Documents\ASP.NET\");
FileInfo[] files = dir.GetFiles("*.txt");
string str = "";
List<string> allfiles = new List<string>();
foreach(FileInfo file in files)
{
str = file.Name;
allfiles.Add(str);
}
return allfiles;
}
}
}
Then, I have a Controller to put the values into the List to pass it to View:
[HttpPost]
public ActionResult Index(string listButton)
{
if (listButton != null)
{
var list = new Lists();
list.ListFiles();
var names = new List<string>();
names = list.ListFiles();
ViewBag.List = names;
return View();
}
}
And I have a View to populate the list:
<button value="List" name="listButton" type="submit" class="btn btn-primary" formmethod="post">List</button>
<ul>
@foreach (var item in (List<string>)ViewBag.List){
<span>
@item
</span>
}
</ul>
But when I'm starting the app, I have an error:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 12: <button value="List" name="listButton" type="submit" class="btn btn-primary" formmethod="post">List</button>
Line 13: <ul>
Line 14: @foreach (var item in (List<string>)ViewBag.List){
Line 15: <span>
Line 16: @item
Source File: c:\Users\Kamm\Documents\ASP.NET\Aplikacja\Aplikacja\Aplikacja\Views\Home\Index.cshtml Line: 14
Can someone help me? I don't know what to do, even if I would like to pass a simple List just from Controller I have the same error.
Solved! I added a line in View:
@if ((List<string>)ViewBag.List != null)
Maybe something is wrong when the app is starting..